HttpClient实现远程调用

       在项目中,咱们经常遇到远程调用的问题,一个模块老是没法单独存在,总须要调用第三方或者其余模块的接口。这里咱们就涉及到了远程调用。 原来在 ITOO中,咱们是经过使用EJB来实现远程调用的,改版以后,咱们用Dubbo+zk来实现。下面介绍一下HttpClient的实现方法。html

(一)简介java

       HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,而且它支持 HTTP 协议最新的版本和建议。能够说是如今Internet上面最重要,使用最多的协议之一了,愈来愈多的java应用须要使用http协议来访问网络资源,特别是如今rest api的流行。apache

(二)使用编程

<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请求api

实现步骤:
第一步:建立一个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
第五步:执行请求。
第六步:接收返回结果
第七步:关闭流。post

 @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测试

相关文章
相关标签/搜索