Skip to content

Instantly share code, notes, and snippets.

@donkarlo
Created September 21, 2016 15:41
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save donkarlo/031108fc26acca658b93f5166bf114b5 to your computer and use it in GitHub Desktop.
package module.concept.home.webservice.jaxrs.jersey;
import com.fasterxml.jackson.core.JsonProcessingException;
import module.concept.home.Home;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HomeServiceClient {
public static void main(String[] args) throws JsonProcessingException {
try {
Home home = new Home("rent", 10, "shz");
String jsonedHome = home.getJsoned(home);
HttpURLConnection httpUrlConn = HomeServiceClient.getHttpUrlConn();
HomeServiceClient.outputStream(httpUrlConn, jsonedHome);
if (httpUrlConn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + httpUrlConn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((httpUrlConn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpUrlConn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static HttpURLConnection getHttpUrlConn() throws MalformedURLException, ProtocolException, IOException {
URL url = new URL("http://localhost:8080/noondreams/homerest/home/insert");
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setRequestMethod("POST");
httpUrlConn.setRequestProperty("Content-Type", "application/json");
return httpUrlConn;
}
private static void outputStream(HttpURLConnection httpUrlConn, String jsonedHome) throws IOException {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(jsonedHome.getBytes());
outputStream.flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment