仅供参考
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HttpClient的主要功能:
(1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
(2)支持自动转向
(3)支持 HTTPS 协议
(4)支持代理服务器等
要知道更多详细的功能可以参见 HttpClient 的主页:
httpClient中文网:link
httpClient 英文:link
实例
1、首先引入HttpClient jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
2、只举例POST
选择jar包的时候,要看仔细
public void HttpTest() throws Exception {//测试远程访问接口
String Url = "http://地址:端口/接口";//设置远程访问路径
//httpClient 来自:import org.apache.http.impl.client.CloseableHttpClient;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(Url);//使用post进行访问 来自:import org.apache.http.client.methods.HttpPost;
InsuranceOrderNo insuranceOrderNo1 = new InsuranceOrderNo();//需要发送的数据,我这里是以对象的形式
StringEntity stringEntity = new StringEntity(JSONObject.fromObject(insuranceOrderNo1).toString()); //声明一个String实体 来自:import org.apache.http.entity.StringEntity; 主要用于完善请求
stringEntity.setContentEncoding("编码格式");
stringEntity.setContentType("访问格式");
post.setEntity(stringEntity);
System.out.println("post访问路径" + post.getURI());
HttpResponse httpResponse = httpClient.execute(post); //执行请求 来自:import org.apache.http.HttpResponse;
String result = EntityUtils.toString(httpResponse.getEntity());//
System.out.println("打印result:"+JSONObject.fromObject(result).toString())//因为我这返回的是json
}
亲测有效哦!