package com.mengyao.spider.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.NameValuePair;

/**
 * 依赖于Apache httpcomponents项目下的HttpClient组件中的httpclient-4.4.jar、httpcore-4.4.jar、commons-logging-1.2.jar
 * @author mengyao
 *
 */
public class HttpUtil {

/**
     * 创建httpClient实例
     * @return
     */
    public CloseableHttpClient getHttpClient() {
        HttpClientBuilder builder = HttpClients.custom();
        CloseableHttpClient client = builder.build();
        return client;
    }
    
    /**
     * 构造Post请求
     * @param url
     * @param params
     * @param encoding
     * @return
     * @throws Exception
     */
    public HttpPost getHttpPost(String url, Map<String, String> params, String encoding) throws Exception{
        HttpPost post = new HttpPost(url);
        List<NameValuePair> parammeters = new ArrayList<NameValuePair>();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        while(iterator.hasNext()){
            Entry<String, String> next = iterator.next();
            parammeters.add(new BasicNameValuePair(next.getKey(), next.getValue()));
        }
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parammeters, encoding);
        post.setEntity(urlEncodedFormEntity);
        
        return post;
    }
    
    /**
     * 构造Get请求
     * @param url
     * @return
     */
    public HttpGet getHttpGet(String url){
        HttpGet get = new HttpGet(url);
        return get;
    }
    
    /**
     * 为Post或Get请求设置Http请求头参数
     * @param postAndGet
     * @param headers
     * @return
     */
    public HttpRequestBase setHeader(HttpRequestBase postAndGet, Map<String, String> headers){
        Iterator<Entry<String, String>> iterator = headers.entrySet().iterator();
        while(iterator.hasNext()){
            Entry<String, String> next = iterator.next();
            postAndGet.addHeader(next.getKey(), next.getValue());
        }
        return postAndGet;
    }
    
    /**
     * 获取Http响应中的响应头参数
     * @param response
     * @return
     */
    public Map<String, String> getHeader(CloseableHttpResponse response){
        Map<String, String> headers = new HashMap<String, String>();
        Header[] allHeaders = response.getAllHeaders();
        for (Header header : allHeaders) {
            headers.put(header.getName(), header.getValue());
        }
        return headers;
    }
    
    /**
     * 获取Http响应中的原生数据
     * @param entity
     * @param consume
     * @return
     * @throws Exception
     */
    public String getRawContent(HttpEntity entity, boolean consume) throws Exception{
        String rawCtx = EntityUtils.toString(entity);
        if (consume) {
            EntityUtils.consume(entity);
        }
        return rawCtx;
    }
    
    /**
     * 释放Http连接
     * @param client
     * @throws Exception
     */
    public void clean(CloseableHttpClient client) throws Exception{
        client.close();
    }
    
    public static void main(String[] args) throws Exception {
        HttpUtil httpUtil = new HttpUtil();
        /************************************* 创建HttpGet请求Begin ***********************************/
        //获取Http实例
        CloseableHttpClient httpClient = httpUtil.getHttpClient();
        //创建HttpGet请求
        HttpGet httpGet = httpUtil.getHttpGet("http://www.jd.com");
        //设置HttpGet请求头参数
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
        httpUtil.setHeader(httpGet, headers);
        //提交HttpGet请求,同时获取Http响应
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //获取Http的响应头参数
        Map<String, String> header = httpUtil.getHeader(response);
        //获取Http响应中的原生数据内容,同时关闭Http底层连接
        String rawContent = httpUtil.getRawContent(response.getEntity(), true);
        //释放本次Http请求实例
        httpUtil.clean(httpClient);
        /************************************* 创建HttpGet请求End ***********************************/
        
        //HttpPost请求与上述代码同理,不做演示
    }
}

Apache HttpClient组件封装工具类的更多相关文章

  1. JAVA之旅(五)——this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块

    JAVA之旅(五)--this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块 周末收获颇多,继续学习 一.this关键字 用于区分局部变量和成员变量同名的情况 ...

  2. Android OkHttp网络连接封装工具类

    package com.lidong.demo.utils; import android.os.Handler; import android.os.Looper; import com.googl ...

  3. 泛型(二)封装工具类CommonUtils-把一个Map转换成指定类型的javabean对象

    1.commons-beanutils的使用 commons-beanutils-1.9.3.jar 依赖 commons-logging-1.2.jar 代码1: String className ...

  4. MySQL JDBC常用知识,封装工具类,时区问题配置,SQL注入问题

    JDBC JDBC介绍 Sun公司为了简化开发人员的(对数据库的统一)操作,提供了(Java操作数据库的)规范,俗称JDBC,这些规范的由具体由具体的厂商去做 对于开发人员来说,我们只需要掌握JDBC ...

  5. 带SSL证书的httpclient 远程接口工具类

    package com.iups.wx.util; import java.io.IOException; import java.io.UnsupportedEncodingException; i ...

  6. FTP上传-封装工具类

    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...

  7. 超简单的okhttp封装工具类(上)

      版权声明:转载请注明出处:http://blog.csdn.net/piaomiao8179 https://blog.csdn.net/piaomiao8179/article/details/ ...

  8. 单机版 RedisUtils({基本操作封装工具类})【三】

    <!--集成的RedisJAR--> <!--引入jedis需的jar包--> <dependency> <groupId>redis.clients& ...

  9. 单机版 JedisUtil({基本操作封装工具类})【二】

    <!--集成的RedisJAR--> <!--引入jedis需的jar包--> <dependency> <groupId>redis.clients& ...

随机推荐

  1. Android 从清单配置文件元数据中获取值

    最近在上班工作当中,也尝到了一些新的知识,现总结如下(1)从AndroidManifest.xml配置文件中获取meta数据 // 从Manifest.xml配置文件中获取数据 public stat ...

  2. android使用微软EWS发送邮件

    通常我们在android使用javamail发送邮件,可是很多时候我们需要连接Exchange服务(很多公司内部邮件服务器采用,并且未开通smtp服务)来发送邮件,这时候我们就要用到微软的 ews-j ...

  3. (转)jquery.validate.js 的 remote 后台验证

    之前已经有一篇关于jquery.validate.js验证的文章,还不太理解的可以先看看:jQuery Validate 表单验证(这篇文章只是介绍了一下如何实现前台验证,并没有涉及后台验证remot ...

  4. if..endif 语法

    使用 if(); elseif(); else; endif; 这一系列复杂的语句无助于 PHP 3.0 解析器的效率.因此,语法改变为: Example#1 移植:旧有 if..endif 语法 i ...

  5. 图文教程:手把手教你用U盘安装Ubuntu

    说到ubuntu,有接触linux的童鞋都应该听过,用wubi安装只是像在电脑上安装一个软件,可以轻松体验ubuntu,不过毕竟性能会打折扣,所以本人是比较喜欢直接安装在硬盘上的. 这种方法只适合用d ...

  6. Swift语言 代码添加文本输入框 和 占位文本

    //懒加载文本输入框 private lazy var textView: UITextView = { let textView = UITextView() textView.font = UIF ...

  7. git add相关

    git add -A stages All git add . stages new and modified, without deleted git add -u stages modified ...

  8. 1.tomcat部署项目的几种方式和weblogic部署方式及一点通讯

      第一种部署方式: 直接使用myeclipse 找到server服务 添加要部署的项目Add Deployment ,然后选中某个项目,首选Exploded Archive(development ...

  9. CentOS 7 之Cisco Anyconnect Secure Mobility Client

    公司使用的是Cisco VPN, 于是准备使用一下.先登录公司的vpn页面,意料之中的失败,所以下载了vpnsetup.sh这个来手动安装. 手动是要用root的,不过由于我是个人学习使用机器,一直用 ...

  10. js中数组去重的几种方法

    js中数组去重的几种方法         1.遍历数组,一一比较,比较到相同的就删除后面的                 function unique(arr){                 ...