Umesh Kacha
Umesh Kacha

Reputation: 13686

Getting JSON response as part of Rest call in Java

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 it's incomplete because I don't know how to process output using JSON.

public static void main(String[] args) {
        try { 
            
            URL url = new URL("http://example.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); 
        } 

    }

I am new to Rest services and JSON.

Upvotes: 6

Views: 38232

Answers (4)

Konzern
Konzern

Reputation: 128

JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class);
System.out.println("jsonkey.getOne() : "+jsonkey.getOne())

Upvotes: -1

Sergey Morozov
Sergey Morozov

Reputation: 4628

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));

Upvotes: 2

djs
djs

Reputation: 53

Since your Content-Type is application/json, you could directly cast the response to a JSON object for example

JSONObject recvObj = new JSONObject(response);

Upvotes: 0

Rahul
Rahul

Reputation: 45080

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.

Upvotes: 3

Related Questions