在项目中,我们常常遇到远程调用的问题,一个模块总是无法单独存在,总需要调用第三方或者其他模块的接口。这里我们就涉及到了远程调用。 原来在 ITOO中,我们是通过使用EJB来实现远程调用的,改版之后,我们用Dubbo+zk来实现。下面介绍一下HttpClient的实现方法。
(一)简介
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。可以说是现在Internet上面最重要,使用最多的协议之一了,越来越多的java应用需要使用http协议来访问网络资源,特别是现在rest api的流行。
(二)使用
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient-cache</artifactId> <version>4.5</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.3.2</version> </dependency>
(三)POST请求
实现步骤:
第一步:创建一个httpClient对象
第二步:创建一个HttpPost对象。需要指定一个url
第三步:创建一个list模拟表单,list中每个元素是一个NameValuePair对象
第四步:需要把表单包装到Entity对象中。StringEntity
第五步:执行请求。
第六步:接收返回结果
第七步:关闭流
@Test public void testHttpPost() throws Exception { // 第一步:创建一个httpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 第二步:创建一个HttpPost对象。需要指定一个url HttpPost post = new HttpPost("http://localhost:8082/posttest.html"); // 第三步:创建一个list模拟表单,list中每个元素是一个NameValuePair对象 List<NameValuePair> formList = new ArrayList<>(); formList.add(new BasicNameValuePair("name", "张三")); formList.add(new BasicNameValuePair("pass", "1243")); // 第四步:需要把表单包装到Entity对象中。StringEntity StringEntity entity = new UrlEncodedFormEntity(formList, "utf-8"); post.setEntity(entity); // 第五步:执行请求。 CloseableHttpResponse response = httpClient.execute(post); // 第六步:接收返回结果 HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity); System.out.println(result); // 第七步:关闭流。 response.close(); httpClient.close(); }
(四)Get请求
实现步骤:
第一步:创建一个httpClient对象
第二步:创建一个HttpPost对象。需要指定一个url
第三步:创建一个list模拟表单,list中每个元素是一个NameValuePair对象
第四步:需要把表单包装到Entity对象中。StringEntity
第五步:执行请求。
第六步:接收返回结果
第七步:关闭流。
@Test public void testHttpGet() throws Exception { // 第一步:把HttpClient使用的jar包添加到工程中。 // 第二步:创建一个HttpClient的测试类 // 第三步:创建测试方法。 // 第四步:创建一个HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 第五步:创建一个HttpGet对象,需要制定一个请求的url HttpGet get = new HttpGet("http://www.itheima.com"); // 第六步:执行请求。 CloseableHttpResponse response = httpClient.execute(get); // 第七步:接收返回结果。HttpEntity对象。 HttpEntity entity = response.getEntity(); // 第八步:取响应的内容。 String html = EntityUtils.toString(entity); System.out.println(html); // 第九步:关闭response、HttpClient。 response.close(); httpClient.close(); }
转载至:https://blog.csdn.net/mengmei16/article/details/72190363?foxhandler=RssReadRenderProcessHandler