在 Java 中作为 Rest 调用的一部分获取 JSON 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19045992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting JSON response as part of Rest call in Java
提问by Umesh K
I am trying to make rest service call in Java. I am new to web and rest service. I have rest service which returns json as response. I have the following code but I think its incomplete because I dont know how to process output using json.
我正在尝试用 Java 进行休息服务调用。我是网络和休息服务的新手。我有休息服务,它返回 json 作为响应。我有以下代码,但我认为它不完整,因为我不知道如何使用 json 处理输出。
public static void main(String[] args) {
try {
URL url = new URL("http://xyz.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);
}
}
Please help. I am new to rest services and json. Thanks a lot in advance.
请帮忙。我是休息服务和 json 的新手。非常感谢。
采纳答案by SudoRahul
Since this is a PUT
request you're missing a few things here:
由于这是一个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.
}
Have a look at thisto have a more clear idea on hitting webservices.
看看这个,对点击网络服务有一个更清晰的想法。
回答by djs
Since your Content-Type is application/json, you could directly cast the response to a JSON object for example
由于您的 Content-Type 是 application/json,因此您可以直接将响应转换为 JSON 对象,例如
JSONObject recvObj = new JSONObject(response);
回答by Sergey Morozov
Your code is mostly correct, but there is mistake about OutputStream
.
As R.J said OutputStream
is needed to pass requestbody to the server.
If your rest service doesn't required any body you don't need to use this one.
您的代码大部分是正确的,但是关于OutputStream
. 正如 RJ 所说OutputStream
,需要将请求正文传递给服务器。如果您的休息服务不需要任何机构,您就不需要使用这个机构。
For reading the server responseyou need use InputStream
(R.J also show you example) like that:
要读取您需要使用的服务器响应InputStream
(RJ 也向您展示了示例),如下所示:
try (InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) {
byte[] buf = new byte[512];
int read = -1;
while ((read = inputStream.read(buf)) > 0) {
byteArrayOutputStream.write(buf, 0, read);
}
System.out.println(new String(byteArrayOutputStream.toByteArray()));
}
This way is good if you don't want to depends on third-part libraries. So I recommend you to take a look on Jersey- very nice library with huge amount of very useful feature.
如果您不想依赖第三方库,这种方式很好。所以我建议你看看Jersey- 非常好的库,有大量非常有用的功能。
Client client = JerseyClientBuilder.newBuilder().build();
Response response = client.target("http://host:port").
path("test").path("db-api").path("processor").path("packages").
request().accept(MediaType.APPLICATION_JSON_TYPE).buildGet().invoke();
System.out.println(response.readEntity(String.class));
回答by Konzern
JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class);
System.out.println("jsonkey.getOne() : "+jsonkey.getOne())