获取 JSON 响应作为 Java 中 Rest 调用的一部分

新手上路,请多包涵

我正在尝试用 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 的新手。

原文由 Umesh K 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 320
2 个回答

因为这是一个 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.
}

看看 这个 可以更清楚地了解如何访问 web 服务。

原文由 Rahul 发布,翻译遵循 CC BY-SA 3.0 许可协议

您的代码大部分是正确的,但关于 OutputStream 有错误。正如 RJ 所说 OutputStream 需要将 请求 主体传递给服务器。如果你的休息服务不需要任何身体,你就不需要使用这个。

要读取服务器 响应,您需要使用 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()));
}

如果您不想依赖第三方库,这种方式很好。所以我建议你看看 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));

原文由 Sergey Morozov 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题