gpt4 book ai didi

java - 使用 HttpURLConnection 执行 POST 请求时获取 JSON 响应

转载 作者:行者123 更新时间:2023-11-30 02:53:06 25 4
gpt4 key购买 nike

我使用以下代码在 REST API 上执行 POST 请求。一切正常。我无法做的是 POST 成功后,API 在正文中返回带有 header 的响应 JSON,该 JSON 包含我需要的信息。我无法获得 JSON 响应。

我需要此响应,因为此响应包含数据库生成的 ID。我可以在使用 Firefox 的 REST 客户端插件时看到响应。需要在 Java 中实现相同的功能。

enter image description here

    String json = "{\"name\": \"Test by JSON 1\",\"description\": \"Test by JSON 1\",\"fields\": {\"field\": []},\"typeDefinitionId\": \"23\",\"primaryParentId\": \"26982\"}";
String url = "http://serv23/api/contents";
URL obj = new URL(url);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

//Setting the Request Method header as POST
con.setRequestMethod("POST");

//Prepairing credentials
String cred= "user123:p@ssw0rd";
byte[] encoded = Base64.encodeBase64(cred.getBytes());
String credentials = new String(encoded);

//Setting the Authorization Header as 'Basic' with the given credentials
con.setRequestProperty ("Authorization", "Basic " + credentials);

//Setting the Content Type Header as application/json
con.setRequestProperty("Content-Type", "application/json");

//Overriding the HTTP method as as mentioned in documentation
con.setRequestProperty("X-HTTP-Method-Override", "POST");

con.setDoOutput(true);

JSONObject jsonObject = (JSONObject)new JSONParser().parse(json);

OutputStream os = con.getOutputStream();
os.write(jsonObject.toJSONString().getBytes());

os.flush();
WriteLine( con.getResponseMessage() );
int responseCode = con.getResponseCode();

最佳答案

获取输入流并读取它。

String json_response = "";
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}

关于java - 使用 HttpURLConnection 执行 POST 请求时获取 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38046429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com