如何从云端获取响应数据到字符串

How to get the response data from cloud to string

我想从云端的数据中获取对字符串变量的响应。

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

我在控制台中收到了 JSON 的响应,我想将其转换为字符串,GSON 库是会有帮助吗?我还没有使用它。我的代码需要做哪些修改?有人可以帮我吗

下面是一个工作示例:

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

          }

    }

事实上,Restlet 以 String 形式接收响应负载,您可以直接访问它,如下所述:

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

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

希望对你有帮助, 蒂埃里