gpt4 book ai didi

java - 使用 httpclientcomponents 向服务器发送 JSON 请求

转载 作者:行者123 更新时间:2023-12-02 04:04:38 24 4
gpt4 key购买 nike

这段代码工作正常...因为我对此进行了很多搜索,所以我决定将此代码放在想要向具有 URL 的服务器发送 json 请求的人中.这是HttpClientComponent

public static boolean sendJsonTo(String URL,JSONObject jo) throws IOException {
CloseableHttpClient httpClient= HttpClientBuilder.create().build();
try {

HttpPost request = new HttpPost(URL);
StringEntity params = new StringEntity(jo.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response=httpClient.execute(request);
} catch (Exception ex) {
ex.printStackTrace();
return false;
// handle exception here
} finally {
httpClient.close();
}
return true;
}

我正在使用this json version

这是 make json 对象的示例代码

public static JSONObject test(String firstname,String lastname){
JSONObject jup=new JSONObject();
jup.put("fname",firstname);
jup.put("lname",lastname);
return jup;
}

最佳答案

处理来自服务器的响应:
试试这个:

HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);

或者像这样

    HttpEntity entity = response.getEntity();

JsonFactory jsonf = new JsonFactory();

// try with resource is not strictly necessary here
// but is a good practice
try(InputStream instream = entity.getContent()) { JsonParser jsonParser = jsonf.createParser(instream);
// Use the parser to deserialize the object from the content stream
return stuff;
}

关于java - 使用 httpclientcomponents 向服务器发送 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34480601/

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