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. javascript中的继承用法

    本文实例汇总了javascript关于继承的用法,希望本文所述对大家的javascript程序设计有所帮助.分享给大家供大家参考.具体如下:代码如下: /** * 实现子类继承父类,但不会产生多余的属 ...

  2. Java基础知识强化79:被遗忘的Java Math类

    1. Math类概述 Math类包含用于执行基本数学运算的方法,如初等指数.对数.平方根和三角函数. 2. 成员变量 和 成员方法(常用的) (1)成员变量 public static final d ...

  3. 线段树---HDU1166敌兵布阵

    这个是线段树中最入门的题目,但是由于不了解线段树的概念,当然更不知道怎么样,所以觉得挺费劲,整了一会发现还是基本的思想,就是还是将一个线段继续分割,一直分割到不能分割,这道题目是知道多少个军营,也就是 ...

  4. 公共Webservice

    网络上可供测试的Web Service腾讯QQ在线状态 WEB 服务Endpoint: http://www.webxml.com.cn/webservices/qqOnlineWebService. ...

  5. ASP.NET-FineUI开发实践-10

    嵌套Grid,光棍月大放送,不藏着掖着.实在写的不好,没脸藏啊~只考虑显示排序修改什么的都不管! 话说三石官网加实例了,http://fineui.com/demo/#/demo/grid/grid_ ...

  6. css ie hack整理

    网上有很多关于ie hack的文章,可能由于文章发布后ie的版本还在升级.所以导致有些hack写法已经不适用了.以下是本人整理的ie6-11的一些hack常用写法.(以下默认文档模式为标准模式) 1. ...

  7. DIV布局之道二:DIV块的嵌套,DIV盒子模型

    本文讲解DIV块布局的第二种使用方式:嵌套.“DIV嵌套”在有些文献中也被称为“盒子模型”,说的通俗一点就是嵌套(一个大的DIV块内部又包含一个或多个DIV块). 请看如下代码: CSS部分: CSS ...

  8. linux jdk,java ee ,tomcat 安装配置

    1.把mypagekage.iso 挂载到linux操作系统中. 在VM做好配置,使用 mount /mnt/cdrom 2.把安装文件拷贝到/home cp 文件名 /home (快捷键tab) 3 ...

  9. Swift - 42 - 类的基本使用

    import Foundation /* 1.class表示类的关键字 2.class后面表示类名 3.类名后面的大括号内表示类的内部 */ /* 1.属性封装了set和get方法 2.方法里面封装了 ...

  10. Php 常用类

    图表库下面的类库可以让你很简单就能创建复杂的图表和图片.当然,它们需要GD库的支持.pChart - 一个可以创建统计图的库.Libchart - 这也是一个简单的统计图库.JpGraph - 一个面 ...