Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取JSON响应作为Java中Rest调用的一部分_Java_Json_Rest - Fatal编程技术网

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

获取JSON响应作为Java中Rest调用的一部分,java,json,rest,Java,Json,Rest,我正在尝试用Java进行rest服务调用。我不熟悉web和rest服务。我有一个rest服务,它返回json作为响应。我有以下代码,但我认为它不完整,因为我不知道如何使用json处理输出 public static void main(String[] args) { try { URL url = new URL("http://xyz.com:7000/test/db-api/processor"); HttpURLCon

我正在尝试用Java进行rest服务调用。我不熟悉web和rest服务。我有一个rest服务,它返回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); 
        } 

    }

请帮忙。我不熟悉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.
}

查看一下,以便更清楚地了解如何访问Web服务。

因为您的内容类型是application/json,所以您可以直接将响应转换为json对象

JSONObject recvObj = new JSONObject(response);

您的代码基本正确,但关于
OutputStream
有错误。 正如R.J所说,需要
OutputStream
请求正文传递给服务器。 如果您的rest服务不需要任何身体,您不需要使用这个

要读取服务器响应,您需要使用
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()));
}
如果您不想依赖第三方库,这种方法是很好的。所以我建议你们去看看——非常好的库,有大量非常有用的特性

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

如果你正在使用Spring,它会让你的生活变得轻松。它将执行HTTP请求,将HTTP响应转换为您选择的对象类型,并返回该对象。
JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class);
System.out.println("jsonkey.getOne() : "+jsonkey.getOne())