使用org.apche.commons.httpclient工具包
maven地址
<dependency>
<groupId>org.kie.modules</groupId>
<artifactId>org-apache-commons-httpclient</artifactId>
<version>6.2.0.CR2</version>
</dependency>
实现代码
public class HttpTool{
public static void httpPost() throes Exception{
//请求内容 json格式的参数,可以将我们要发送的内容转换为json格式
String paramsJson = "";
/*服务端通常是根据请求头(headers)中的Content-Type字段来获知请求中的消息主体是用何种方式编码,再对主体进行解析。所以说到POST提交数据方案,包含了Content-Type和消息主体编码方式两部分*/
//客户端实例化
HttpClient client = new HttpClient();
//请求方法post,可以将请求路径传入构造参数中
PostMethod postMethod = new PostMethod("http://...");
//设置请求头
postMethod.addRequestHeader("Content-type","application/json;charset=utf-8");
//将参数转为二进制
byte[] requestBytes = paramsJson.getBytes("utf-8");
InputStream inputStream = new ByteArrayInputStream(requestBytes,0,requestBytes.length);
//设置请求体
RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,requestBytes.length,"application/json;charset=utf-8");
//执行方法 这里可以根据请求状态判断请求是否成功,然后根据第三方接口返回的数据格式,解析出我们需要的数据
int i = client.executeMethod(postMethod);
//得到响应数据
byte[] responseBody = postMethod.getResponseBody();
String s = new String(responseBody);
}
}