httpclient4的封装

HttpClient 4.0  GET POST 封装

 

 package org.lujian.webqq.utils;

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
*
* @author lujian
*/
public class WEB {

  HttpClient httpclient;
  HttpResponse response;

  public List<Cookie> getCookies() {
    return ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
  }

  public Map<String,String> getMapCookies() {
    Map<String,String> map = new HashMap<String,String>();
    List<Cookie> cookies = ((AbstractHttpClient)httpclient).getCookieStore().getCookies();
    for (Cookie c : cookies) {
      map.put(c.getName(), c.getValue());
    }
    return map;
  }

  public String getCookie(String key) {
    for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore()
        .getCookies()) {
      if (c.getName().equals("key"))
        return c.getValue();
    }
    return null;
  }

  
  // /
  public WEB() {
    httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
        CookiePolicy.BROWSER_COMPATIBILITY);
  }

  public String get(String url) throws Exception {
    HttpGet httpget = new HttpGet(url);
    response = httpclient.execute(httpget);
    HttpEntity httpEntity = response.getEntity();
    String html = null;
    if (httpEntity != null) {
      html = EntityUtils.toString(httpEntity);
      httpEntity.consumeContent();
    }
    return html;
  }
  
  public String post(String url, List<NameValuePair> nvps) throws Exception {
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    response = httpclient.execute(httppost);
    HttpEntity httpEntity = response.getEntity();
    String html = null;
    if (httpEntity != null) {
      html = EntityUtils.toString(httpEntity);
      httpEntity.consumeContent();
    }
    return html;
  }

  @SuppressWarnings("unchecked")
  public String post(String url, Map map) throws IOException {
    List<NameValuePair> nvps = new ArrayList();
    Iterator it = map.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry entry = (Map.Entry) it.next();
      String key = (String) entry.getKey();
      String value = (String) entry.getValue();
      NameValuePair nvp = new BasicNameValuePair(key, value);
      nvps.add(nvp);
    }
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    response = httpclient.execute(httppost);
    HttpEntity httpEntity = response.getEntity();
    String html = null;
    if (httpEntity != null) {
      html = EntityUtils.toString(httpEntity);
      httpEntity.consumeContent();
    }
    return html;
  }

  public String post(String url, String str) throws Exception {
    httpclient.getConnectionManager().closeIdleConnections(30,
        TimeUnit.SECONDS);
    HttpPost httppost = new HttpPost(url);// "http://web-proxy.qq.com/conn_s"
    StringEntity reqEntity = new StringEntity(str);
    httppost.setEntity(reqEntity);
    response = httpclient.execute(httppost);
    HttpEntity httpEntity = response.getEntity();
    String html = null;
    if (httpEntity != null) {
      html = EntityUtils.toString(httpEntity);
      httpEntity.consumeContent();
    }
    return html;
  }

  public void getImg(String url, String path) throws IOException {
    HttpGet httpget = new HttpGet(url);
    response = httpclient.execute(httpget);
    HttpEntity httpEntity = response.getEntity();
    byte[] b = EntityUtils.toByteArray(httpEntity);
    File storeFile = new File(path);
    FileOutputStream output = new FileOutputStream(storeFile);
    output.write(b);
    output.close();
    if (httpEntity != null) {
      httpEntity.consumeContent();
    }
  }

  public void close() throws IOException {
    httpclient.getConnectionManager().shutdown();
  }
}

 

httpclient4的封装

添加了gzip压缩数据的处理
对基本的get,post及获取文件及post字符串进行了封装
httpclient4  lib包请到http://hc.apache.org/下载
或配置maven自动获取:

引用
     <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.0</version>
        </dependency>  



 

package org.lujian.base.http;

/**
* @author lujian
*/
public interface WebHeaderConstant {
    //
    public final static String WEB_ACCEPT_XML = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    public final static String WEB_ACCEPT_JSON = "application/json, text/javascript, */*";
    public final static String WEB_ACCEPT_CHARSET = "GBK,utf-8;q=0.7,*;q=0.3";
    public final static String WEB_ACCEPT_ENCODING = "gzip,deflate,sdch";
    public final static String WEB_ACCEPT_LANGUAGE = "zh-CN,zh;q=0.8";
    public final static String WEB_CONTENT_TYPE = "application/x-www-form-urlencoded; charset=UTF-8";
    public final static String WEB_USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.84 Safari/534.13 By LuJian's Client";
    public final static String WEB_X_REQUESTED_WITH = "XMLHttpRequest";
}


 

========================================================================

package org.lujian.base.http;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.params.*;
import org.apache.http.conn.params.*;
import org.apache.http.entity.*;
import org.apache.http.entity.mime.*;
import org.apache.http.entity.mime.content.*;
import org.apache.http.impl.client.*;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.*;

/**
* http访问 封装
* @author lujian
*/
public class HttpWebClient {

    private String charset = "GBK";
    private HttpClient httpclient;

    /**
     * 构造方法
     */
    public HttpWebClient() {
        httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
    }

    /**
     * 构造方法
     * @param charset
     */
    public HttpWebClient(String charset) {
        this();
        this.charset = charset;
    }

    /**
     * 构造方法 :使用代理连接
     * @param ip
     * @param port
     */
    public HttpWebClient(String ip, int port) {
        this();
        HttpHost proxy = new HttpHost(ip, port);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    private HttpGet setHttpGetHeader(HttpGet httpGet, Map<String, Object> headers) {
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue().toString());
            }
        }
        return httpGet;
    }

    public String get(HttpGet httpget) throws IOException {
        HttpResponse response = httpclient.execute(httpget);
        return this.getResponseBodyAsString(response);
    }

    public String get(Map<String, Object> headers, String url) throws IOException {
        HttpGet httpget = new HttpGet(url);
        httpget = this.setHttpGetHeader(httpget, headers);
        return this.get(httpget);
    }

    private String get(String url, String headerAccept) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", headerAccept);
        return this.get(headers, url);
    }

    public String get(String url) throws IOException {
        return this.get(url, WebHeaderConstant.WEB_ACCEPT_XML);
    }

    public String getJson(String url) throws IOException {
        return this.get(url, WebHeaderConstant.WEB_ACCEPT_JSON);
    }

    public byte[] getFile(HttpGet httpget) throws IOException {
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        byte[] bs = EntityUtils.toByteArray(entity);
        if (entity != null) {
            entity.consumeContent();
        }
        return bs;
    }

    public byte[] getFile(Map<String, Object> headers, String url) throws IOException {
        HttpGet httpget = new HttpGet(url);
        httpget = this.setHttpGetHeader(httpget, headers);
        return this.getFile(httpget);
    }

    public byte[] getFile(String url) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
        return this.getFile(headers, url);
    }

    public byte[] getFile(String url, File file) throws IOException {
        byte[] bs = this.getFile(url);
        FileOutputStream output = new FileOutputStream(file);
        output.write(bs);
        output.close();
        return bs;
    }

    private HttpPost setHttpPostHeaderAndParams(HttpPost httpPost, Map<String, Object> headers, Map<String, Object> params) throws UnsupportedEncodingException {
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue().toString());
            }
        }
        //
        List nvps = new ArrayList<NameValuePair>();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                  nvps.add(new NameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        return httpPost;
    }

    public String post(HttpPost httppost) throws IOException {
        HttpResponse response = httpclient.execute(httppost);
        return this.getResponseBodyAsString(response);
    }

    public String post(Map<String, Object> headers, String url, Map<String, Object> params) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        this.setHttpPostHeaderAndParams(httpPost, headers, params);
        return this.post(httpPost);
    }

    public String post(String url, Map<String, Object> params) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
        return this.post(headers, url, params);
    }

    public String postJson(String url, Map<String, Object> params) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_JSON);
        return this.post(headers, url, params);
    }

    public String post(HttpPost httppost, String str) throws IOException {
        StringEntity reqEntity = new StringEntity(str);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        return this.getResponseBodyAsString(response);
    }

    public String post(Map<String, Object> headers, String url, String str) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        this.setHttpPostHeaderAndParams(httpPost, headers, null);
        return this.post(httpPost, str);
    }

    public String post(String url, String str) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
        return this.post(headers, url, str);
    }

    public String postJson(String url, String str) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_JSON);
        return this.post(headers, url, str);
    }

    public String uploadFile(HttpPost httppost, File file) throws IOException {
        FileBody fileBody = new FileBody(file);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", fileBody);
        // 设置请求
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        return this.getResponseBodyAsString(response);
    }

    public void close() {
        httpclient.getConnectionManager().shutdown();
    }

    // ///
    public HttpClient getHttpclient() {
        return httpclient;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    private String getResponseBodyAsString(HttpResponse response) throws IOException {
        String html = null;
        GZIPInputStream gzin;
        if (response.getEntity().getContentEncoding() != null && response.getEntity().getContentEncoding().getValue().toLowerCase().indexOf("gzip") > -1) {
            InputStream is = response.getEntity().getContent();
            gzin = new GZIPInputStream(is);

            InputStreamReader isr = new InputStreamReader(gzin, "iso-8859-1");
            java.io.BufferedReader br = new java.io.BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String tempbf;
            while (( tempbf = br.readLine() ) != null) {
                sb.append(tempbf);
                sb.append("\r\n");
            }
            isr.close();
            gzin.close();
            html = sb.toString();
            html = new String(html.getBytes("iso-8859-1"), this.charset);
        } else {
            HttpEntity entity = response.getEntity();
            html = EntityUtils.toString(entity, this.charset);
            if (entity != null) {
                entity.consumeContent();
            }
        }
        return html;
    }

    private Map<String, Object> getCommonHeader() {
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("Accept-Charset", WebHeaderConstant.WEB_ACCEPT_CHARSET);
        headers.put("Accept-Encoding", WebHeaderConstant.WEB_ACCEPT_ENCODING);
        headers.put("Accept-Language", WebHeaderConstant.WEB_ACCEPT_LANGUAGE);
        headers.put("User-Agent", WebHeaderConstant.WEB_USER_AGENT);
        return headers;
    }
}

refer from:http://blog.lujian.org/post/95/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值