springboot使用httpclient(PostMethod,RequestEntity等)需要导入哪些jar包
原创
©著作权归作者所有:来自51CTO博客作者chushiyunaaa的原创作品,请联系作者获取转载授权,否则将追究法律责任
所需jar包如下:
commons-codec-1.7.jar
commons-logging-1.1.1.jar
commons-httpclient.jar
httpclient-4.2.2.jar
httpcore-4.2.2.jar
如果有spring-boot-starter-parent
,下面2个默认会带:
commons-codec-1.7.jar
commons-logging-1.1.1.jar
所以pom.xml只需要引入如下:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.1</version>
</dependency>
httpClient设置header
注:setHeader()或者setRequestHeader() 都是会累加的,不用专门弄个header体。
写法一:
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(req, StandardCharsets.UTF_8);
httpPost.setEntity(stringEntity);
httpPost.setHeader("appID", appID);
httpPost.setHeader("customKey", "customValue");
response = httpClient.execute(httpPost);
写法二:
PostMethod postMethod = new PostMethod(url);
byte[] b = req.getBytes("utf-8");
InputStream is = new ByteArrayInputStream(b, 0, b.length);
RequestEntity re = new InputStreamRequestEntity(is, b.length,
"text/xml; charset=utf-8");
postMethod.setRequestHeader("customKey","customValue");
postMethod.setRequestEntity(re);
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
int statusCode = httpClient.executeMethod(postMethod);