httpClient

package com.bizyi.crm.pub.http;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.util.StopWatch;
import com.bizyi.pub.log.LogManager;
import com.bizyi.pub.log.RunLevel;

public class HttpClient
{
    private final static HttpClient instance = new HttpClient();
   
    private HttpClient()
    {
       
    }
   
    public final static HttpClient getIntance()
    {
        return instance;
    }
   
    /**
     * xml格式的
     *
     * @param in
     * @param httpurl
     * @return InputStream
     */
    public InputStream executeHTTP(InputStream in, String httpurl)
    {
        String fullName = "HttpClient:executeHTTP";
        PostMethod postMethod = new PostMethod(httpurl);
        postMethod.setRequestHeader("Connection", "close");
        RequestEntity requestEntity = new InputStreamRequestEntity(in, "text/html;charset=UTF-8");
        postMethod.setRequestEntity(requestEntity);
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        InputStream retStream = null;
        StopWatch stopWatch = new StopWatch("HTTPClient:httpurl");
        stopWatch.start();
        try
        {
            httpClient.executeMethod(postMethod);
            stopWatch.stop();
            retStream = postMethod.getResponseBodyAsStream();
        }
        catch (HttpException e)
        {
            LogManager.runLog(RunLevel.INFO(), fullName + "http execute failed", e);
        }
        catch (IOException e)
        {
            LogManager.runLog(RunLevel.INFO(), fullName + "http io exeception", e);
        }
        return retStream;
    }
   
    /**
     *
     * @param httpurl
     * @param username
     * @param ip
     * @param sessionId
     * @return
     */
    public InputStream executeHTTP(String httpurl, String username, String ip, String sessionId)
    {
        String fullName = "HttpClient:executeHTTP";
        PostMethod postMethod = new PostMethod(httpurl);
        LogManager.runLog(RunLevel.INFO(), httpurl + "url&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&" + fullName);
        // 设置头文件的编码
        postMethod.setRequestHeader("ContentType", "text/html;charset=utf-8");
        //postMethod.setRequestHeader("Connection", "close");
        //设置post参数
        NameValuePair usname = new NameValuePair("userName", username);
        NameValuePair i = new NameValuePair("localIP", ip);
        NameValuePair sId = new NameValuePair("sessionId", sessionId);
        postMethod.setRequestBody(new NameValuePair[] { i, usname, sId });
        //设置参数的字符编码
        postMethod.getParams().setContentCharset("utf-8");
        // 多线程模式模式下使用httpclient
        MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(manager);
        InputStream retStream = null;
        //是设置系统参数
        HttpClientParams httpClientParams = new HttpClientParams();
        // 设置读取内容时间超时
        httpClientParams.setSoTimeout(10000);
        // 设置系统提供的默认恢复策略,在发生异常时候将自动重试3次
        httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
       
        httpClient.setParams(httpClientParams);
        // 设置连接超时
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
        httpClient.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(32);
        // 设置最大连接数
        httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(256);
        // 统计调用接口时间
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try
        {
            // 返回的状态码
            httpClient.executeMethod(postMethod);
            // 检查是否重定向
            int statuscode = postMethod.getStatusCode();
            // 301 SC_MOVED_PERMANENTLY 页面已经永久移到另外一个新地址
            // 302 SC_MOVED_TEMPORARILY 页面暂时移动到另外一个新的地址
            // 303 SC_SEE_OTHER 客户端请求的地址必须通过另外的 URL 来访问
            // 307 SC_TEMPORARY_REDIRECT 同 SC_MOVED_TEMPORARILY
            if (statuscode == HttpStatus.SC_MOVED_PERMANENTLY || statuscode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statuscode == HttpStatus.SC_SEE_OTHER || statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)
            {
                // 读取新的地址
                Header header = postMethod.getResponseHeader("location");
                if (null != header)
                {
                    String newuri = header.getValue();
                    if (null == newuri || "".equals(newuri))
                    {
                        newuri = "/";
                        PostMethod post = new PostMethod(newuri);
                        httpClient.executeMethod(post);
                        retStream = post.getResponseBodyAsStream();
                    }
                    else
                    {
                        LogManager.runLog(RunLevel.INFO(), "invalid rediect");
                    }
                }
            }
            stopWatch.stop();
           
            retStream = postMethod.getResponseBodyAsStream();
        }
        catch (HttpException e)
        {
            LogManager.runLog(RunLevel.ERROR(), fullName + "http 协议异常  failed", e);
        }
        catch (IOException e)
        {
            LogManager.runLog(RunLevel.ERROR(), fullName + "http io exeception", e);
        }
        finally
        {
            // 释放连接
            // /postMethod.releaseConnection();
        }
        return retStream;
    }
   
    /**
     * 呼出的方法
     * @param httpurl
     * @param module
     * @param action
     * @param exten
     * @param call_num
     * @return inputStream
     */
    public InputStream executeHTTP(String httpurl, String exten, String call_num)
    {
        String fullName = "HttpClient:executeHTTP";
        PostMethod postMethod = new PostMethod(httpurl);
        // 设置头文件的编码
        postMethod.setRequestHeader("ContentType", "text/html;charset=UTF-8");
        //设置参数
        NameValuePair etn = new NameValuePair("exten", exten);
        NameValuePair phone = new NameValuePair("call_num", call_num);
        postMethod.setRequestBody(new NameValuePair[] { etn, phone });
        //设置参数的字符编码
        postMethod.getParams().setContentCharset("utf-8");
        // 多线程模式模式下使用httpclient
        MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(manager);
        InputStream retStream = null;
        HttpClientParams httpClientParams = new HttpClientParams();
        // 设置读取内容时间超时
        httpClientParams.setSoTimeout(10000);
        // 设置系统提供的默认恢复策略,在发生异常时候将自动重试3次
        httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        httpClient.setParams(httpClientParams);
        // 设置连接超时
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
       
        httpClient.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(32);
        // 设置最大连接数
        httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(256);
        // 统计调用接口时间
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try
        {
            // 返回的状态码
            httpClient.executeMethod(postMethod);
            // 检查是否重定向
            int statuscode = postMethod.getStatusCode();
            // 301 SC_MOVED_PERMANENTLY 页面已经永久移到另外一个新地址
            // 302 SC_MOVED_TEMPORARILY 页面暂时移动到另外一个新的地址
            // 303 SC_SEE_OTHER 客户端请求的地址必须通过另外的 URL 来访问
            // 307 SC_TEMPORARY_REDIRECT 同 SC_MOVED_TEMPORARILY
            if (statuscode == HttpStatus.SC_MOVED_PERMANENTLY || statuscode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statuscode == HttpStatus.SC_SEE_OTHER || statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)
            {
                // 读取新的地址
                Header header = postMethod.getResponseHeader("location");
                if (null != header)
                {
                    String newuri = header.getValue();
                    if (null == newuri || "".equals(newuri))
                    {
                        newuri = "/";
                        PostMethod post = new PostMethod(newuri);
                        httpClient.executeMethod(post);
                        retStream = post.getResponseBodyAsStream();
                    }
                    else
                    {
                        LogManager.runLog(RunLevel.INFO(), "invalid rediect");
                    }
                }
            }
            stopWatch.stop();
           
            retStream = postMethod.getResponseBodyAsStream();
        }
        catch (HttpException e)
        {
            LogManager.runLog(RunLevel.ERROR(), fullName + "http 协议异常  failed", e);
        }
        catch (IOException e)
        {
            LogManager.runLog(RunLevel.ERROR(), fullName + "http io exeception", e);
        }
        finally
        {
            // 释放连接
            // /postMethod.releaseConnection();
        }
        return retStream;
    }
}
s

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值