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

bqf10yzr  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(402)

我想从云中的数据中得到对字符串变量的响应。

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库会有帮助吗?我还没用过。我的代码需要做什么修改?有人能帮我吗。

ojsjcaue

ojsjcaue1#

实际上,restlet以字符串形式接收响应负载,您可以直接访问它,如下所述:

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

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

希望对你有帮助,蒂埃里

bt1cpqcv

bt1cpqcv2#

下面是一个工作示例:

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

          }

    }

相关问题