springboot:在post请求时使用params附加json

brvekthn  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(457)

我需要做个决定 POST 使用params请求并附加json内容。
截至目前:

CloseableHttpClient client = HttpClients.createDefault();

HttpPost httpPost = new HttpPost("http://localhost:8983/solr/arxius/update");

List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("commitWithin", "1000"));
params.add(new BasicNameValuePair("overwrite", "true"));
params.add(new BasicNameValuePair("wt", "json"));

String json = "...";
// here I need to attach json as body...

try {
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    CloseableHttpResponse response = client.execute(httpPost);
    client.close();
} catch (IOException e) {

    e.printStackTrace();
}

在这里 curl 类似请求:

curl 'http://localhost:8983/solr/arxius/update?_=1605619902909&commitWithin=1000&overwrite=true&wt=json'
  -H 'Content-type: application/json'
  --data-raw $'[{ "id": ... }]'
5jvtdoz2

5jvtdoz21#

使用stringentity:

StringEntity se = new StringEntity(json, org.apache.commons.lang3.CharEncoding.UTF_8);              
httpPost.setEntity(se);

一种自包含的、可重复的实体,从字符串中获取其内容。
供参数使用 URIBuilder :

URIBuilder uriBuilder = new URIBuilder("http://localhost:8983/solr/arxius/update");
uriBuilder.addParameter("commitWithin",  "1000");
...
HttpHost httpPost = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());

相关问题