-2

I want to get the response to a string variable from the data from the cloud.

ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
try {
    try {
        cr.get(MediaType.APPLICATION_JSON).write(System.out);
    } catch (IOException e) {

        e.printStackTrace();
    }
} catch (ResourceException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I have response as JSON in the console and I want to convert it to string , Is the GSON library would be helpful? I haven't used it yet .What modifications should I need to do in my codes? Can anybody help me here.

George Netu
  • 2,662
  • 4
  • 26
  • 49
Viz_Kid
  • 85
  • 1
  • 1
  • 7

2 Answers2

0

Below is a working example:

 try {

            URL url = new URL("http://localhost:8888/users");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

            String output;
            System.out.println("Raw Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

          } catch (MalformedURLException e) {

            e.printStackTrace();

          } catch (IOException e) {

            e.printStackTrace();

          }

    }
Rami Del Toro
  • 981
  • 6
  • 21
0

In fact, Restlet receives the response payload as String and you can directly have access to this, as described below:

ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);   

Representation representation = cr.get(MediaType.APPLICATION_JSON);
String jsonContentAsString = representation.getText();

Hope it helps you, Thierry

Thierry Templier
  • 182,931
  • 35
  • 372
  • 339