HttpClient 的使用

HttpClient使用:

maven:

      <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

code:

package com.qhong.http;

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 ="utf-8";
    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", "utf-8");
        client.getParams().setContentCharset("utf-8");
        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(),"utf-8"));
            String line = null;
            String html = null;
            while((line = reader.readLine()) != null){
                if(html == null) {
                    html = "";
                } else {
                    html += "
";
                }
                html += line;
            }
            if(html != null) {
                result = new String(html.getBytes("utf-8"), 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;
    }
}

test:

package com.qhong.http;

import java.util.HashMap;
import java.util.Map;

public class test {

    public static void main(String[] args) throws Exception{
        HttpInvoker httpInvoker=HttpInvoker.getInstance();
        //Get
        String content  = httpInvoker.invoke("http://www.baidu.com");
        System.out.println(content);
        //Post
        Map<String,String> params=new HashMap<String,String>();
        params.put("a","testDFRZW952");
        params.put("na","Zn+4A+yXAfrT847NjCToRg==");
        params.put("pe","sFt/8rWLN1F+Fd8RTnc9eA==");
        params.put("pv","上海市");
        params.put("cy","上海");
        params.put("la","120000");
        String url="http://jwebplat.momead.com/d/call/info";
        String content2=httpInvoker.invoke(url,params,true);
        System.out.println(content2);
    }
}

上面test中的map参数,在请求体中的显示为:

a=testDFRZW952&na=Zn%2B4A%2ByXAfrT847NjCToRg%3D%3D&pe=sFt%2F8rWLN1F%2BFd8RTnc9eA%3D%3D&la=120000&pv=%E4%B8%8A%E6%B5%B7%E5%B8%82&cy=%E4%B8%8A%E6%B5%B7

如果想使用json方式请求,这个工具类还不合适

package com.qhong.http;

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLDecoder;


public class HttpRequestUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);    //日志记录
    
    /**
     * httpPost
     *
     * @param url       路径
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) {
        return httpPost(url, jsonParam, false);
    }


    /**
     * post请求
     *
     * @param url            url地址
     * @param jsonParam      参数
     * @param noNeedResponse 不需要返回结果
     * @return
     */

    public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse) {
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
           /**请求发送成功,并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.fromObject(str);
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        }
        return jsonResult;
    }


    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */

    public static JSONObject httpGet(String url) {
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.fromObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return jsonResult;
    }
}

http://www.cnblogs.com/ITtangtang/p/3968093.html

http://blog.csdn.net/hwwzyh/article/details/39184677

http://www.cnblogs.com/QQParadise/articles/5020215.html

原文地址:https://www.cnblogs.com/hongdada/p/7779166.html