httpClient4.3x版本的简单使用

1、主要使用对象:

  1.  HttpClient:客户端

  2. HttpGetHttpPost:两种请求

  3. RequestConfig:请求配置

  4. HttpResponse:请求返回体

2、一般使用方法

  1. 创建客户端

  2. 配置客户端参数

  3. 创建get 或post 请求

  4. 设置请求参数如:添加cookie,请求头

  5. 执行请求,得到HttpResponse对象

  6. 解析HttpResponse,获取需要数据

    下面将所有的操作放在一个自己写的工具类中:

public class NetRequest {
 
 HttpClient client;
 HttpGet get;
 HttpPost post;
 HttpResponse response;
 
 boolean isGet = false;
 boolean isPost = false;
 
 public NetRequest() {
  client = HttpClientBuilder.create().build();
  
 }
 
 /**
  * 设置Get 请求
  * @param url
  * @param params
  * @return
  */
 public NetRequest setGet(String url,Map<String, Object> params){
  if(isPost){  
   client = HttpClientBuilder.create().build();
  }
  URI uri = setURI(url, params);
  get = new HttpGet(uri);
  isGet = true;
  isPost = false;
  return this;
 }
 
 /**
  * 设置Post请求
  * @param url
  * @param params
  * @return
  */
 public NetRequest setPost(String url,Map<String, Object> params){
  if(isGet){ 
   client = HttpClientBuilder.create().build();
  }
  URI uri = setURI(url, null);
  HttpEntity entity = setEntity(params);
  post = new HttpPost(uri);
  post.setEntity(entity);
  isGet = false;
  isPost = true;
  return this;
 }
 
 /**
  * 添加请求头
  * @param name
  * @param value
  * @return
  */
 public NetRequest addHead(String name,String value){
  if(isGet){
   get.addHeader(name, value);
  }
  if(isPost){
   post.addHeader(name, value);
  }
  return this;
 }
 
 /**
  * 添加Cookie
  * @param cookie
  * @return
  */
 public NetRequest addCookie(String cookie){
  addHead("Cookie", cookie);
  return this;
 }
 
 /**
  * 设置请求配置
  * @param config
  * @return
  */
 public NetRequest setRequestConfig(RequestConfig config){
  if(isGet){
   get.setConfig(config);
  }
  if(isPost){
   post.setConfig(config);
  }
  return this;
 }
 
 /**
  * 设置请求超时
  * @param conTime 连接
  * @param socketTime 数据传输
  * @return
  */
 public NetRequest setConnectiontime(int conTime,int socketTime){
  RequestConfig config = RequestConfig.custom().setConnectTimeout(conTime).setSocketTimeout(socketTime).build();
  return setRequestConfig(config);
 }
 
 /**
  * 执行请求
  * @return
  */
 public NetRequest doRequest(){
  //response = null;
  try{
   if(isGet){
    response = client.execute(get);
   }
   if(isPost){
    response = client.execute(post);
   }
  }catch(Exception e){
   e.printStackTrace();
  }
  
  return this;
 }
 
 /**
  * 获取返回字符串
  * @return
  */
 public String getStr(){
  try{
            HttpEntity entity = response.getEntity();
            String body = EntityUtils. toString(entity);
             return body;
      } catch(Exception e){
             e.printStackTrace();
             return null;
      }
 }
 
 
 public HttpResponse getResponse(){
  return response;
 }
 
 /**
  * 下载文件
  * @param file
  * @return
  */
 public  File getFile(File file){
        try{
             InputStream inputStream = response.getEntity().getContent();
             OutputStream outputStream = new FileOutputStream(file);
             int index = 0;
              byte[] btys = new byte[4096];
              while(( index = inputStream.read( btys)) != -1){
                    outputStream.write( btys, 0, index);
             }
              inputStream.close();
              outputStream.flush();
              outputStream.close();
              return file;
       } catch(Exception e){
              return null;
       }
 }
 
    public  File getFile(String filePath){
           try{
                File file = new File( filePath);
                 if(! file.exists()){
                       if(! file.getParentFile().exists()){
                             file.getParentFile().mkdirs();
                      }
                       file.createNewFile();
                }
                 return getFile(file);
          } catch(Exception e){
                 e.printStackTrace();
                 return null;
          }
          
    }
 
 
 /**
     * 设置参数 --在URI中
     * @param url
     * @param params
     * @return
     */
    public static URI setURI(String url,Map<String, Object> params){
           try{
                 if(! url.startsWith( "http")){
                       url = "http://" + url;
                }
                URIBuilder builder = new URIBuilder( url);
                 if( params == null){
                       return builder.build();
                }
                Set<String> keys = params.keySet();
                 for (String key : keys) {
                      Object object = params.get( key);
                       if( object.getClass().equals(File. class)){
                            
                      } else{
                             builder.addParameter( key, object.toString());
                      }
                }
                 return builder.build();
          } catch(Exception e){
                 e.printStackTrace();
                 return null;
          }
    }
    
    /**
     * 设置参数 --包含文件上传
     * @param params
     * @return
     */
    public static HttpEntity setEntity(Map<String, Object> params){
          MultipartEntityBuilder builder = MultipartEntityBuilder.create();
           builder.setMode(HttpMultipartMode. BROWSER_COMPATIBLE);//浏览器兼容模式
           try{
                 builder.setCharset(CharsetUtils. get("UTF-8" )); //设置编码
          } catch(Exception e){
                
          }
          Set<String> keys = params.keySet();
           for (String key : keys) {            
                Object object = params.get( key);                    
              if(object == null )
                    continue;              
                 if( object.getClass().equals(File. class)){
                      FileBody fileBody = new FileBody((File) object);
                       builder.addPart( key, fileBody);
                } else if(object.getClass().equals(String.class)){
                 
                      StringBody stringBody = new StringBody(object.toString(), ContentType.TEXT_PLAIN);
                      builder.addPart( key, stringBody);
                }
          }
           return builder.build();
    }
}

测试用例:

  NetRequest netRequest = new NetRequest();
  String sign = baseUrl + "/sign/mysign?page=1&step=1000&type=1";
  JSONArray array = JSONArray.parseArray(netRequest.setGet(sign, null).addCookie("JSESSIONID=9A5611188E3E25193DF1F848A012957D").doRequest().getStr());

 

 

 

转载于:https://my.oschina.net/u/2476827/blog/596430

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值