我想从云中的数据中获取对字符串变量的响应。
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 库是否有用?我还没用过。我的代码需要做哪些修改?任何人都可以帮助我。
答案 0 :(得分:0)
以下是一个工作示例:
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();
}
}
答案 1 :(得分:0)
实际上,Restlet将响应有效负载作为String接收,您可以直接访问它,如下所述:
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
Representation representation = cr.get(MediaType.APPLICATION_JSON);
String jsonContentAsString = representation.getText();
希望它可以帮到你, 亨利