【问题标题】:Getting JSON response as part of Rest call in Java在 Java 中作为 Rest 调用的一部分获取 JSON 响应
【发布时间】:2013-09-27 08:17:31
【问题描述】:

我正在尝试用 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); 
        } 

    }

请帮忙。我是休息服务和 json 的新手。提前非常感谢。

【问题讨论】:

标签: java json rest


【解决方案1】:

由于这是一个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 以更清楚地了解如何使用 Web 服务。

【讨论】:

    【解决方案2】:

    您的代码大部分是正确的,但OutputStream 有错误。 正如 R.J 所说,OutputStream 需要将 request 正文传递给服务器。 如果你的休息服务不需要任何身体,你就不需要使用这个。

    要读取服务器响应,您需要像这样使用InputStream(R.J 也向您展示示例):

    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));
    

    【讨论】:

      【解决方案3】:

      由于您的 Content-Type 是 application/json,您可以直接将响应转换为 JSON 对象,例如

      JSONObject recvObj = new JSONObject(response);
      

      【讨论】:

        【解决方案4】:
        JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class);
        System.out.println("jsonkey.getOne() : "+jsonkey.getOne())
        

        【讨论】:

          猜你喜欢
          • 2021-10-15
          • 2021-05-10
          • 1970-01-01
          • 2016-12-15
          • 2016-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多