重点:
如果和以下问题匹配参考此博客
- 请求为参数为json 格式传输,且请求头的content-type为application/json
- 请求参数为key/value结构
pom坐标
content-type 为 application/json格式org.apache.httpcomponents httpclient4.5.13
若传输JSON格式需要使用httpClient的StringEntity ,且请求头的content-type需要设置为application/json
ps:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://127.0.0.1:9090");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
httpPost.setHeader("content-type", "application/json");
HashMap map = new HashMap<>();
map.put("a", "1");
map.put("b","2");
// map 转为JSON
ObjectMapper objectMapper = new ObjectMapper();
String asString = objectMapper.writeValueAsString(map);
StringEntity entity = new StringEntity(asString,"UTF-8");
httpPost.setEntity(entity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String string = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println(string);
httpResponse.close();
httpClient.close();
key/value
需要使用UrlEncodedFormEntity类
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://127.0.0.1:9090");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
ArrayList pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("a", "1"));
pairs.add(new BasicNameValuePair("b","2"));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
httpPost.setEntity(urlEncodedFormEntity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String string = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println(string);
httpResponse.close();
httpClient.close();



