Java 如何从云到字符串获取响应数据
我想从云数据中获取对字符串变量的响应Java 如何从云到字符串获取响应数据,java,json,gson,google-cloud-storage,restlet,Java,Json,Gson,Google Cloud Storage,Restlet,我想从云数据中获取对字符串变量的响应 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.print
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以字符串形式接收响应负载,您可以直接访问它,如下所述:
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
Representation representation = cr.get(MediaType.APPLICATION_JSON);
String jsonContentAsString = representation.getText();
希望它能帮助你,
蒂埃里是的,我已经得到了答案,无论如何,非常感谢蒂埃里:)