最近在项目中,一直在使用HttpClient 中的方法,这里我进行一些方法的汇总,也是结合了一些大牛写的代码,以备不时之需

  官话:HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议

       在我的博客我的常用工具了中有关于httpclient 的常用方法,在平常的开发中是足够用了----------在这里我细致的总结一下

 

  1.我们在使用httpclient 第一步就是创建CloseableHttpClient 实例,这也是官方推荐方法:

 CloseableHttpClient httpclient = HttpClients.createDefault()

  2.创建 httpget 与 httppost 的实例,我们进行网络连接的关键步骤:

//post 请求
HttpPost httppost =new HttpPost(url); // get请求 HttpGet httpget =new HttpGet(url);

  3. addHeader(arg0, arg1)  :见名知意,可以为我们请求加上请求头,cookie

//加cookie 头

httppost.addHeader("Cookie","JSESSIONID=fnwebidwn==");

//User-Agent

httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");

......

  4.   httppost.setEntity(entity); 放入需要传递的参数,只出现在post 方法中,因为get直接在地址后面追加参数。

   httppost 我们常用三种都是需要我们掌握的

        1.传递json 类型的字符串

        2.传递form表单

        3.Multipart/form-data 类型 的数据

 

    (1),第一个比较简单,就是将我们的json参数转换为字符串进行传递,这个不多讲,使用过微信接口就应该不会陌生,很简单的

// outstr 是json字符串类型的参数,
httppost.setEntity(new StringEntity(outstr, "UTF-8"));

    (2),第二种传递form 表单,类似于我们form 表单提交的POST 请求,将参数进行了封装,使用时候必须将参数封装

                    ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); 中

    
//在集合中放入我们表单中的name --- value 键值对

List<BasicNameValuePair> pair =new ArrayList<BasicNameValuePair>();
pair.add(new BasicNameValuePair("name", "value"));
pair.add(new BasicNameValuePair("name2", "value2"));
pair.add(new BasicNameValuePair("name3", "value3"));



//-------工作中一般将参数封装在Map中,我们遍历Map往 BasicNameValuePair 集合中放入

List<BasicNameValuePair> pair =new ArrayList<BasicNameValuePair>();

   //我们遍历map 将数据转化为我们的表单数据
      for (Map.Entry<String,String> entry:
          map.entrySet()) {
         pair.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
      }

//httppost 中放入我们的经过url编码的表单参数

httppost.setEntity(new UrlEncodedFormEntity(pair));

    (3). 传递Multipart/form-data 类型 的数据,这种数据类型在文件上传中使用的,类似有form 表单设置了 enctype="multipart/form-data",   默认表单是  application/x-www-form-urlencoded

      关于这两个的区别:multipart/form-data ,用于文件的上传,设置表单的MIME编码,二进制传输数据,参数会以boundary进行分割

               application/x-www-form-urlencoded:不能进行文件的上传,我们一般form表单默认就是这个类型

               一般只要不涉及到文件上传,建议还是使用默认 application/x-www-form-urlencoded 我们第二种提交方式 

//创建 MultipartEntityBuilder,以此来构建我们的参数 
MultipartEntityBuilder EntityBuilder = MultipartEntityBuilder.create();
//设置字符编码,防止乱码
ContentType contentType=ContentType.create("text/plain",Charset.forName("UTF-8"));
//填充我们的文本内容,这里相当于input 框中的 name 与value
EntityBuilder.addPart("name", new StringBody("value",contentType));
EntityBuilder.addPart("name1", new StringBody("value1",contentType));
EntityBuilder.addPart("name2", new StringBody("value2",contentType));
//上传我们的文件
EntityBuilder.addBinaryBody("filename", new File("C:\\Users\\Administrator\\Desktop\\testImg.png"));
//参数组装
post.setEntity(EntityBuilder.build());

  这样,三种常见的参数提交方式就OK了,亲测可用哦;

 

  5.参数post.setEntity("entity对象“”)封装好之后,就是进行发送网络请求了 ,返回  HttpResponse  

HttpResponse response=httpclient.execute(post);

   6.接下来就是解析返回来的  HttpResponse ,有很多办法,但是我看到很多大牛写到这里解析 HttpResponse 时候,都会创建一个实现了 ResponseHandler 的处理器,进行 

  自己编码后续的处理;如下: 

package com.project.utils;

import java.io.IOException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;


public class Utf8ResponseHandler implements ResponseHandler<String> {

    /*
     *实现utf-8编码的返回数据类型,实现ttpclient ResponseHandler接口方法
     *
     *copy from {@link org.apache.http.impl.client.BasicResponseHandler}官方默认提供
     */
    public static final ResponseHandler<String> INSTANCE = new Utf8ResponseHandler();
    
    @Override
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
         final StatusLine statusLine = response.getStatusLine();
            final HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
              EntityUtils.consume(entity);
              throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            return entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);
          }
    
    
    }

 

   其中:

  

response.getStatusLine().getStatusCode()//可以获得服务的响应码

HttpEntity entity = response.getEntity() //获取响应的对象内容

EntityUtils.toString(entity, Consts.UTF_8) //进行相应内容文本展示并编码
 

  7. 完成之后,释放资源

    

finally {
                
                httppost.releaseConnection();
            }

 

 

 

..........................这就是HttpClient 完整的一套流程

 

      

 

posted on 2018-09-05 22:34  iscys  阅读(15245)  评论(0编辑  收藏  举报