簡體   English   中英

SpringBoot:使用參數在 POST 請求上附加 json

[英]SpringBoot: Attach json on POST request with params

我需要使用參數發出POST請求並附加 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": ... }]'

使用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());    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM