我正在尝试用 Java 调用 Rest 服务。我是网络和休息服务的新手。我有 Rest 服务,它返回 JSON 作为响应。我有以下代码,但我认为它不完整,因为我不知道如何使用 JSON 处理输出。
public static void main(String[] args) {
try {
URL url = new URL("http://example.com:7000/test/db-api/processor");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/json");
OutputStream os = connection.getOutputStream();
//how do I get json object and print it as string
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
我是 Rest 服务和 JSON 的新手。
最佳答案
因为这是一个 PUT
请求,所以您在这里遗漏了一些东西:
OutputStream os = conn.getOutputStream();
os.write(input.getBytes()); // The input you need to pass to the webservice
os.flush();
...
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream()))); // Getting the response from the webservice
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output); // Instead of this, you could append all your response to a StringBuffer and use `toString()` to get the entire JSON response as a String.
// This string json response can be parsed using any json library. Eg. GSON from Google.
}
看看this对点击网络服务有更清晰的想法。
关于java - 获取 JSON 响应作为 Java 中 Rest 调用的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19045992/