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. Java基础知识强化24:Java中异常

    1.什么是异常 ?       Java程序运行中,常常会遇到非正常的现象,这种情况称为运行错误.根据性质可以分为错误和异常.Java程序中(无论谁写的代码),所有抛出(throw)的异常都必须从Th ...

  2. Linux 多网卡的7种bond模式原理

    Linux 多网卡绑定 网卡绑定mode共有七种(0~6) bond0.bond1.bond2.bond3.bond4.bond5.bond6 常用的有三种 mode=0:平衡负载模式,有自动备援,但 ...

  3. 【字符串匹配】UVALive 4670 模板题

    给一个文本T,和n个模板字符串,都是由小写字母组成,问这些字符串那些在字符串中出现的次数最多,输出最多的次数以及相应的字符串. AC自动机的模板题,递归输出的时候改成累加次数统计数组cnt即可. 大白 ...

  4. Topcoder SRM 637 (Div.2)

    A.GreaterGameDiv2 不能更水 #line 7 "GreaterGameDiv2.cpp" #include<cstdio> #include <c ...

  5. PHP编写的SVN类

    <?php /** * SVN 外部命令 类 * * @author rubekid * * @todo comment need addslashes for svn commit * */ ...

  6. maven第7章生命周期和插件

    maven插件用到哪些思想? 7.7 从命令行调用插件 目标前缀和插件前缀是一个意思. 在本地搭建maven环境,熟悉maven的环境.

  7. php数组操作函数

    array 详解PHP ob_start()函数的功能要点 http://developer.51cto.com/art/200912/166834.htm http://blog.csdn.net/ ...

  8. asp.net微信开发第十篇----使用百度编辑器编辑图文消息,上传图片、微信视频

    经过几天的资料收集,终于完成了该编辑器的图片上传,视频插入功能,视频插入功能主要借用了该编辑器的插入iframe功能,如原始插件图: 修改后的插件图如下(其中我隐藏掉了一些不需要使用的插件功能): 配 ...

  9. CSS3 2D转换

    CSS3 转换 通过CSS3转换,我们能够对元素进行移动.缩放.转动.拉长或拉伸. 它如何工作? 转换是是元素改变形状.尺寸和位置的一种效果. 你可以使用2D或3D转换你的元素. 浏览器支持 属性 浏 ...

  10. Python文件之----CSV

    # -*- coding:utf-8 -*- ''' Created on 2015年4月20日 @author: liuxue ''' import csv import sys reload(sy ...