HttpClient使用学习

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.httpclient. * ;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.GetMethod;

import java.util.Iterator;
import java.util.Map;
import java.net.SocketTimeoutException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class HttpInvoker {
    private Log logger = LogFactory.getLog(HttpInvoker.class);
    private static HttpInvoker httpInvoker = new HttpInvoker();
    private HttpClient client = null;
    private String charset = "gbk";
    private int timeout = 10000;
    private boolean useProxy = false;
    private String proxyHost = null;
    private int proxyPort;
    private String proxyUsername = null;
    private String proxyPassword = null;
    private boolean initialized = false;

    public static HttpInvoker getInstance() {
        return httpInvoker;
    }

    private HttpInvoker() {
        client = new HttpClient(new MultiThreadedHttpConnectionManager());
        client.getParams().setParameter("http.protocol.content-charset", "gbk");
        client.getParams().setContentCharset("gbk");
        client.getParams().setSoTimeout(timeout);
    }

    public HttpInvoker(String charset, int timeout, boolean useProxy,
        String proxyHost, int proxyPort, String proxyUsername,
        String proxyPassword) {
        client = new HttpClient(new MultiThreadedHttpConnectionManager());
        if (charset != null && !charset.trim().equals("")) {
            this.charset = charset;
        }
        if (timeout > 0) {
            this.timeout = timeout;
        }
        client.getParams().setParameter("http.protocol.content-charset", charset);
        client.getParams().setContentCharset(charset);
        client.getParams().setSoTimeout(timeout);
        if (useProxy && proxyHost != null &&
            !proxyHost.trim().equals("") && proxyPort > 0) {
            HostConfiguration hc = new HostConfiguration();
            hc.setProxy(proxyHost, proxyPort);
            client.setHostConfiguration(hc);
            if (proxyUsername != null && !proxyUsername.trim().equals("") &&
                proxyPassword != null && !proxyPassword.trim().equals("")) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
            }
        }
        initialized = true;
        logger.debug("HttpInvoker初始化完成");
    }

    public synchronized void init() {
        if (charset != null && !charset.trim().equals("")) {
            client.getParams().setParameter("http.protocol.content-charset", charset);
            client.getParams().setContentCharset(charset);
        }
        if (timeout > 0) {
            client.getParams().setSoTimeout(timeout);
        }
        if (useProxy && proxyHost != null &&
            !proxyHost.trim().equals("") && proxyPort > 0) {
            HostConfiguration hc = new HostConfiguration();
            hc.setProxy(proxyHost, proxyPort);
            client.setHostConfiguration(hc);
            if (proxyUsername != null && !proxyUsername.trim().equals("") &&
                proxyPassword != null && !proxyPassword.trim().equals("")) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
            }
        }
        initialized = true;
        logger.debug("HttpInvoker初始化完成");
    }

    public String invoke(String url)throws Exception {
        return invoke(url, null, false);
    }

    public String invoke(String url, Map params, boolean isPost)throws Exception {
        logger.debug("HTTP调用[" + (isPost ? "POST" : "GET") + "][" + url + "][" + params + "]");
        HttpMethod httpMethod = null;
        String result = "";
        try {
            if (isPost && params != null && params.size() > 0) {
                Iterator paramKeys = params.keySet().iterator();
                httpMethod = new PostMethod(url);
                NameValuePair[]form = new NameValuePair[params.size()];
                int formIndex = 0;
                while (paramKeys.hasNext()) {
                    String key = (String)paramKeys.next();
                    Object value = params.get(key);
                    if (value != null && value instanceof String && !value.equals("")) {
                        form[formIndex] = new NameValuePair(key, (String)value);
                        formIndex++;
                    } else if (value != null && value instanceof String[] &&
                        ((String[])value).length > 0) {
                        NameValuePair[]tempForm =
                            new NameValuePair[form.length + ((String[])value).length - 1];
                        for (int i = 0; i < formIndex; i++) {
                            tempForm[i] = form[i];
                        }
                        form = tempForm;
                        for (String v : (String[])value) {
                            form[formIndex] = new NameValuePair(key, (String)v);
                            formIndex++;
                        }
                    }
                }
                ((PostMethod)httpMethod).setRequestBody(form);
            } else {
                if (params != null && params.size() > 0) {
                    Iterator paramKeys = params.keySet().iterator();
                    StringBuffer getUrl = new StringBuffer(url.trim());
                    if (url.trim().indexOf("?") > -1) {
                        if (url.trim().indexOf("?") < url.trim().length() - 1 &&
                            url.trim().indexOf("&") < url.trim().length() - 1) {
                            getUrl.append("&");
                        }
                    } else {
                        getUrl.append("?");
                    }
                    while (paramKeys.hasNext()) {
                        String key = (String)paramKeys.next();
                        Object value = params.get(key);
                        if (value != null && value instanceof String && !value.equals("")) {
                            getUrl.append(key).append("=").append(value).append("&");
                        } else if (value != null && value instanceof String[] &&
                            ((String[])value).length > 0) {
                            for (String v : (String[])value) {
                                getUrl.append(key).append("=").append(v).append("&");
                            }
                        }
                    }
                    if (getUrl.lastIndexOf("&") == getUrl.length() - 1) {
                        httpMethod = new GetMethod(getUrl.substring(0, getUrl.length() - 1));
                    } else {
                        httpMethod = new GetMethod(getUrl.toString());
                    }
                } else {
                    httpMethod = new GetMethod(url);
                }
            }
            client.executeMethod(httpMethod);
            // result = httpMethod.getResponseBodyAsString();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                        httpMethod.getResponseBodyAsStream(), "ISO-8859-1"));
            String line = null;
            String html = null;
            while ((line = reader.readLine()) != null) {
                if (html == null) {
                    html = "";
                } else {
                    html += "\r\n";
                }
                html += line;
            }
            if (html != null) {
                result = new String(html.getBytes("ISO-8859-1"), charset);
            }
        } catch (SocketTimeoutException e) {
            logger.error("连接超时[" + url + "]");
            throw e;
        }
        catch (java.net.ConnectException e) {
            logger.error("连接失败[" + url + "]");
            throw e;
        }
        catch (Exception e) {
            logger.error("连接时出现异常[" + url + "]");
            throw e;
        }
        finally {
            if (httpMethod != null) {
                try {
                    httpMethod.releaseConnection();
                } catch (Exception e) {
                    logger.error("释放网络连接失败[" + url + "]");
                    throw e;
                }
            }
        }

        return result;
    }

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

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public void setProxyPort(int proxyPort) {
        this.proxyPort = proxyPort;
    }

    public void setProxyUsername(String proxyUsername) {
        this.proxyUsername = proxyUsername;
    }

    public void setProxyPassword(String proxyPassword) {
        this.proxyPassword = proxyPassword;
    }

    public void setUseProxy(boolean useProxy) {
        this.useProxy = useProxy;
    }

    public synchronized boolean isInitialized() {
        return initialized;
    }
}

使用方式:post

Map<String,String> params = new HashMap<String,String>();
params.put("check", check);
String result = httpInvoker.invoke( "someURL", params, true);

使用方式:get

String content  = httpInvoker.invoke(url);
时间: 2024-10-11 06:16:34

HttpClient使用学习的相关文章

关于HttpClient的学习心得,请求参数中文乱码问题

最近调用了一个第三方接口,接口文档限定是 HTTPS post 请求 参数是 json格式.然后随便在网上找了一份HttpClient的工具代码,然后直接调用post的请求,参数也觉得没有问题,返回值也正常,但是后来发现参数中的中文全部变成了问号传递过去了,后来发现是参数传递时编码没有指定,现记录下来以供以后学习查看,有遇到和我一样问题的初学者可以减少差询问题的时间. 代码如下: HttpClient httpClient = null; HttpPost httpPost = null; St

webService 使用 httpClient httpCore 学习

一种基于http协议使用WebService方法 首先我们先下载一个叫SoapUI的软件 (直接百度) 安装这个就不用多说. 使用: 1.创建一个SOAP project 填入WSDL 然后会解析出来一些数据.找到我们想要对接的接口 比如我对接的方法是 双击打开是: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.o

Httpclient的学习(一)

1.名词解释 抓包: 抓包(packet capture)就是将网络传输发送与接收的数据包进行截获.重发.编辑.转存等操作,也用来检查网络安全.抓包也经常被用来进行数据截取等. Httpclient: 支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议.一般用来网上抓包或者模拟登陆用的.

android通过HttpClient与服务器JSON交互

通过昨天对HttpClient的学习,今天封装了HttpClient类 代码如下: package com.tp.soft.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apach

小小图片爬虫

前言 事前准备 项目结构 项目环境 项目说明 项目目录 项目编码 页面 indexjsp comcjmservlet CatchPciture comcjmmodel JsonFormat MyHttpClient Picture comcjmutils PictureDownload PictureDownloadMachine 最后再说几句 资源下载路径 前言 通过对HttpClient的学习,打开了我对后台的理解,在我的眼中,后台不再是依赖前端的存在,它可以是一种无浏览器,无APP界面的存

爬虫概念与编程学习之如何爬取视频网站页面(用HttpClient)(二)

先看,前一期博客,理清好思路. 爬虫概念与编程学习之如何爬取网页源代码(一) 不多说,直接上代码. 编写代码 运行 <!DOCTYPE html><html><head><meta http-equiv="X-UA-Compatible" content="IE=Edge" /><meta http-equiv="Content-Type" content="text/html; c

Android学习笔记--使用Apache HttpClient实现网络下载效果,附带进度条显示

今天学习 了Apache 写了一个网络下载的效果,代码如下,代码中我已经写了很详细的注释了,相信大家都能看懂 1 http://m.blog.csdn.net/article/details?id=52927536 2 3 4 package com.wuxianedu.httpdemo; 5 6 import android.app.ProgressDialog; 7 import android.content.Intent; 8 import android.net.Uri; 9 impo

Android学习笔记(四五):互联网通信-HttpClient、XML解析(W3C)

前几日Android发布了4.0 Icecream,昨天上网发现Begining Book中有Edition 3的版本,比对一下,还是有相当的改动,不仅仅增加了tablet的部分,对原有的章节有有一些修订,前后的调整等等.先按Edtion 2的顺序看,相同章节的看Edtion 3,然后回头看Edition 3的Chapter 24.25(E2的36).26.27.28.29.44.45.46.47几个新增章节.同时将模拟器改为Android 2.3的版本,已适应可能新增的改动. 访问Intern

Android学习笔记之HttpClient实现Http请求....

PS:最近光忙着考试了....破组成原理都看吐了....搞的什么也不想干...写篇博客爽爽吧....貌似明天就考试了...sad... 学习笔记: 1.如何实现Http请求来实现通信.... 2.解决Android 2.3 版本以后无法使用Http请求问题....   这里我使用HttpClient来开发Http程序来完成简单的网络通信....其实使用HttpUrlConnection也可以实现,不过HttpClient可以完成HttpUrlConnection的所有功能,并且还自己增加了其他的