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. 使用 Spring 2.5 基于注解驱动的 Spring MVC--转

    概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Spring 2.5 又为 Spring MVC 引入了注解驱动功能.现在你无须让 Controller 继承任何接口,无需在 ...

  2. 【JavaScript】深入分析JavaScript的关系运算和if语句

    JavaScript的关系运算,没有我原想的那么简单.等终于理清它的运算逻辑之后,我的头大了至少一圈.而if语句的真假判定逻辑本身不难,但要把它和关系运算联系起来,相信你会和我一样,到达崩溃边缘.不信 ...

  3. [转] GPS坐标转换经纬度及换算方法

    GPS坐标和经纬度的算法和概率不太一样,但是我们可能会将他们互通起来用,下面先贴上我做的转换工具:http://map.yanue.net/gps.html.里面实现了gps到谷歌地图百度地图经纬度的 ...

  4. java byte数组与int,long,short,byte转换

    public class DataTypeChangeHelper { /** * 将一个单字节的byte转换成32位的int * * @param b * byte * @return conver ...

  5. JavaScript arguments类数组

    1. 什么是类数组 arguments 是一个类数组对象.代表传给一个function的参数列表.  我们来传一个实例. function printArgs() { console.log(argu ...

  6. EventBus 事件总线 案例

    简介 地址:https://github.com/greenrobot/EventBus EventBus是一个[发布 / 订阅]的事件总线.简单点说,就是两人[约定]好怎么通信,一人发布消息,另外一 ...

  7. Spring.net--很棒的事务处理

    1--Case 比如t_Order订单表1,t_OrderDetail订单明细表2 下一张订单会往表1插入一条数据,表2会插入多行数据 使用Spring.net事务管理 例如 ---Order---订 ...

  8. C#里巧用DateTime预设一些可选的日期范围(如本年度、本季度、本月等)

    //大家在做报表或查询的时候都会有给用户预设一些可选的日期范围(如上图)                //如本年度销售额.本季度利润.本月新增客户                //C#里内置的Da ...

  9. Linq使用GroupBy筛选数据

    StringBuilder sb = new StringBuilder(); List<IGrouping<string, modle>> listRepeat = mode ...

  10. The account '' has no team with ID ''

    Xcode 升级到7.2 版本,真机测试的时候报错:The account '' has no team with ID '' 解决办法1:http://stackoverflow.com/quest ...