繁体   English   中英

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

[英]Getting JSON response as part of Rest call in Java

我正在尝试用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。 非常感谢提前。

由于这是一个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.
}

看看这个有关于点击webservices的更清晰的想法。

你的代码大多是正确的,但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()));
}

如果您不想依赖于第三方库,这种方式很好。 所以我建议你看看泽西岛 - 非常好的图书馆,有很多非常有用的功能。

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

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

JSONObject recvObj = new JSONObject(response);
JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class);
System.out.println("jsonkey.getOne() : "+jsonkey.getOne())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM