Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting JSON response as part of Rest call in Java

Tags:

java

json

rest

I am trying to make rest service call in Java. I am new to web and rest service. I have rest service which returns json as response. I have the following code but I think its incomplete because I dont know how to process output using json.

public static void main(String[] args) {
        try { 

            URL url = new URL("http://xyz.com:7000/test/db-api/processor"); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
            connection.setDoOutput(true); 
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("PUT"); 
            connection.setRequestProperty("Content-Type", "application/json"); 

            OutputStream os = connection.getOutputStream(); 
           //how do I get json object and print it as string
            os.flush(); 

            connection.getResponseCode(); 
            connection.disconnect(); 
        } catch(Exception e) { 
            throw new RuntimeException(e); 
        } 

    }

Please help. I am new to rest services and json. Thanks a lot in advance.

like image 858
Umesh K Avatar asked Sep 27 '13 08:09

Umesh K


2 Answers

Since this is a PUT request you're missing a few things here:

OutputStream os = conn.getOutputStream();
os.write(input.getBytes()); // The input you need to pass to the webservice
os.flush();
...
BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream()))); // Getting the response from the webservice

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
    System.out.println(output); // Instead of this, you could append all your response to a StringBuffer and use `toString()` to get the entire JSON response as a String.
    // This string json response can be parsed using any json library. Eg. GSON from Google.
}

Have a look at this to have a more clear idea on hitting webservices.

like image 165
Rahul Avatar answered Oct 31 '22 13:10

Rahul


Your code is mostly correct, but there is mistake about OutputStream. As R.J said OutputStream is needed to pass request body to the server. If your rest service doesn't required any body you don't need to use this one.

For reading the server response you need use InputStream(R.J also show you example) like that:

try (InputStream inputStream = connection.getInputStream();
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) {
    byte[] buf = new byte[512];
    int read = -1;
    while ((read = inputStream.read(buf)) > 0) {
        byteArrayOutputStream.write(buf, 0, read);
    }
    System.out.println(new String(byteArrayOutputStream.toByteArray()));
}

This way is good if you don't want to depends on third-part libraries. So I recommend you to take a look on Jersey - very nice library with huge amount of very useful feature.

    Client client = JerseyClientBuilder.newBuilder().build();
    Response response = client.target("http://host:port").
            path("test").path("db-api").path("processor").path("packages").
            request().accept(MediaType.APPLICATION_JSON_TYPE).buildGet().invoke();
    System.out.println(response.readEntity(String.class));
like image 43
Sergey Morozov Avatar answered Oct 31 '22 14:10

Sergey Morozov