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

标签 java json 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 的新手。

最佳答案

因为这是一个 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对点击网络服务有更清晰的想法。

关于java - 获取 JSON 响应作为 Java 中 Rest 调用的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19045992/

相关文章:

perl - Mojolicious - 无法在 RESTful 中解析 JSON

java - 用户表、评级表和位置表之间的关系是什么?

java - SharedPreferences 不保存文本值

ruby-on-rails - 使用引用对象树查询结果 - Ruby on Rails

java - 如何修复 Junit 和 Mockito 中的 'Argument(s) are different! Wanted' 错误

java - 作为 jar 文件运行时返回字符串作为 JSON 响应失败并显示 500 状态代码

java - 如何用java实现高效的矩阵数据结构?

java - 返回通用结果<Foo<Bar>>

python - 如何使用 json 数据更新现有的 json 文件 python

javascript - 使用 javascript 在嵌套的 JSON 对象中添加或删除特定节点