首页 > 代码库 > HTTPClient

HTTPClient

public class HTTPClient 
{
    private static final Logger logger = LoggerFactory.getLogger(HTTPClient.class);
    public static final int DEFAULT_CONN_TIMEOUT = 10;
    public static final int DEFAULT_READ_TIMEOUT = 30;
    
    private HttpClient httpClient;
    private HttpParams httpParams;
    
    public HTTPClient(HttpClient client) {
        this.httpClient = client;
        this.httpParams = httpClient.getParams();
    }
    
    /**
     * 创建默认的SoapClient实例,连接超时=5秒,读取超时=5秒
    * @return SoapClient
     */
    public static HTTPClient createSoapClient() {
        return createSoapClient(DEFAULT_CONN_TIMEOUT, DEFAULT_READ_TIMEOUT);
    }
    
    /**
     * 创建SoapClient实例
    * @param connTimeout 连接超时, 单位:秒
    * @param readTimeout 读取超时, 单位:秒
    * @return SoapClient
     */
    public static HTTPClient createSoapClient(int connTimeout, int readTimeout) {
        HttpClient httpClient = createHttpClient(connTimeout, readTimeout);
        return new HTTPClient(httpClient);
    }
    
    public static HTTPClient createSoapClient(HttpClient httpClient) {
        return new HTTPClient(httpClient);
    }
    
    public void closeConnection()
    {
        if (httpClient != null){
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    
    /**
     * 创建HttpClient实例。
     * HttpClient连接超时时间为1000,读取数据超时时间为1000
     * @param connTimeout 连接超时, 单位:秒
     * @param readTimeout 读取超时, 单位:秒
     */
    public static HttpClient createHttpClient(int connTimeout, int readTimeout) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, connTimeout*1000);
        HttpConnectionParams.setSoTimeout(httpParams, readTimeout*1000);
        return httpClient;
    }
    
    public static HttpClient createHttpClient(HttpParams httpParams) {
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }
    
    
    public String doPost(String uri, String soapRequestMsg) throws IOException, ConnectTimeoutException{
        return sendPostRequest(uri, soapRequestMsg, HTTP.UTF_8);
    }

    public String sendPostRequest(String uri, String soapRequestMsg, String charset) throws IOException {
        if (uri == null || soapRequestMsg == null){
            throw new IllegalArgumentException("uri or sendPostRequest is null");
        }
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Content-Type", "text/xml; charset=utf-8");
        httpPost.addHeader("SOAPAction", "");
        httpPost.setHeader("aaa", "bbb");
        HttpEntity entity = new StringEntity(soapRequestMsg, charset);
        httpPost.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = getHttpClient().execute(httpPost, responseHandler);
        String responseString = responseBody;        
        logger.debug("sendSoapRequest responseBody=" + responseString);
        return responseString;
    }
    
    /**
     * 得到当前时间给定模式的格式字符串
     * @return
     */
    public static String getTimeString(String pattern){
        String timeString = "";
        DateFormat df = new SimpleDateFormat(pattern);
        timeString = df.format(new Date());
        return timeString;
    }
    
    public String doPut(String uri, String soapRequestMsg) throws IOException, ConnectTimeoutException{
        return sendPutRequest(uri, soapRequestMsg, HTTP.UTF_8);
    }

    public String sendPutRequest(String uri, String soapRequestMsg, String charset) throws IOException {
        if (uri == null || soapRequestMsg == null){
            throw new IllegalArgumentException("uri or soapRequestMsg is null");
        }
        HttpPut httpPut = new HttpPut(uri);
        httpPut.setHeader("OIP-Sender", "34.1107");
        HttpEntity entity = new StringEntity(soapRequestMsg, charset);
        httpPut.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = getHttpClient().execute(httpPut, responseHandler);
        String responseString = responseBody;        
        logger.debug("responseBody=" + responseString); 
        logger.debug("sendSoapRequest responseBody=" + responseString);
        return responseString;
    }
    
    /**  
     * 将字符串编码格式转成GB2312  
     * @param str  
     * @return  
     */  
    private String tranEncodeTOUTF8(String str) {   
        try {   
            String strEncode = getEncoding(str);  
            logger.debug("responseBody encode is " + strEncode);
            String temp = new String(str.getBytes(strEncode), "UTF-8");   
            return temp;   
        } catch (java.io.IOException ex) {   
  
            return null;   
        }   
    }   
  
    /**  
     * 判断输入字符是否为gb2312的编码格式
     * @param c 输入字符  
     * @return 如果是gb2312返回真,否则返回假  
     */  
    private boolean isUTF8(String str) {   
        char cChar = str.charAt(0); 
        Character ch = new Character(cChar);   
        String sCh = ch.toString();   
        try {   
            byte[] bb = sCh.getBytes("UTF-8");   
            if (bb.length > 1) {   
                return true;   
            }   
        } catch (java.io.UnsupportedEncodingException ex) {   
            return false;   
        }   
        return false;   
    }   
  
    /**
     * 判断应答报文的编码是否是指定编码
     * @param encode
     * @return
     */
    private boolean checkResponseEncodeIfThisEncode(String responseStr,String encode){
        boolean ret = false;
        try {   
            if (responseStr.equals(new String(responseStr.getBytes(encode), encode))) {   
                ret = true;   
            }   
        } catch (Exception exception) {             
        }
        
        return ret;
    }
    /**  
     * 判断字符串的编码  
     * @param str  
     * @return  
     */  
    private String getEncoding(String responseStr) {   
        String encode = "GB2312";  
        if(checkResponseEncodeIfThisEncode(responseStr,encode)){
            return encode;
        }
        /** ISO 拉丁字母表 No.1,也叫作 ISO-LATIN-1 */   
        encode = "ISO-8859-1";   
        if(checkResponseEncodeIfThisEncode(responseStr,encode)){
            return encode;
        }
        /** 8 位 UCS 转换格式 */
        encode = "UTF-8";   
        if(checkResponseEncodeIfThisEncode(responseStr,encode)){
            return encode;
        }
        /** 中文超大字符集 */
        encode = "GBK";   
        if(checkResponseEncodeIfThisEncode(responseStr,encode)){
            return encode;
        }
        /** 7位ASCII字符,也叫作ISO646-US、Unicode字符集的基本拉丁块 */
        encode = "US-ASCII";   
        if(checkResponseEncodeIfThisEncode(responseStr,encode)){
            return encode;
        }
        /** 16 位 UCS 转换格式,字节顺序由可选的字节顺序标记来标识 */
        encode = "UTF-16";   
        if(checkResponseEncodeIfThisEncode(responseStr,encode)){
            return encode;
        }
        /** 16 位 UCS 转换格式,Big Endian(最低地址存放高位字节)字节顺序 */
        encode = "UTF-16BE";   
        if(checkResponseEncodeIfThisEncode(responseStr,encode)){
            return encode;
        }
        /** 16 位 UCS 转换格式,Little-endian(最高地址存放低位字节)字节顺序 */
        encode = "UTF-16LE";   
        if(checkResponseEncodeIfThisEncode(responseStr,encode)){
            return encode;
        }
        
        return "";   
    }  
    
    
    /**
     * @return the httpClient
     */
    public HttpClient getHttpClient() {
        if (httpClient == null){
            httpClient = createHttpClient(httpParams);
        }
        return httpClient;
    }

    /**
     * @param httpClient the httpClient to set
     */
    public void setHttpClient(HttpClient httpClient) {
        this.httpClient = httpClient;
    }
    
    
    
    /**
     * @description 发送Http请求
     * @param request
     * @return
     */
    private  String sendRequest(HttpUriRequest request) {
        HttpClient client = new DefaultHttpClient();
        String line = null;
        StringBuffer sb = new StringBuffer();
        try {
            HttpResponse res = client.execute(request);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                InputStreamReader isr = new InputStreamReader(
                        entity.getContent(), HTTP.UTF_8);
                BufferedReader bufr = new BufferedReader(isr);// 缓冲
                while ((line = bufr.readLine()) != null) {
                    sb.append(line);
                }
                isr.close();
            }
        } catch (Exception e) {
            logger.error("HTTP服务存在异常,请检查http地址是否能访问!!", e);
            throw new RuntimeException(e);
        } finally {
            // 关闭连接 ,释放资源
            client.getConnectionManager().shutdown();
        }
        return sb.toString();
    }
    
    
    /**
     * @description 向指定的URL发起一个GET请求并以String类型返回数据,获取数据总线数据
     * @param url
     * @return
     */
    public  String doGet(String url) {
        HttpGet request = new HttpGet(url);
        request.setHeader("OIP-Sender", "34.1107");
        return sendRequest(request);
    }
    
    
    public static void main(String[] args) {
        HTTPClient  soapClient  =HTTPClient.createSoapClient(1000,1000);
        String url ="http://192.168.80.212:9008";
        String sendCmdContent="wangkun";
        String str ="\"interfaceName\":\"BatchTfjNotice\"{\"msg\":{\"RequestMsg\":{\"BatchNo\":\"123456789\",\"BatchSize\":\"100\",\"CreateTime\":\"2014-12-01 23:01:23\",\"ProvinceNo\":\"8000123\",\"DataLocation\":\"1\",\"DataURI\":\"http://134.64.115.26:8080/CINASResell_MsgNoticModule/dataBusGet.jsp\"}}}";
        try {
            String soapResponse = soapClient.doPost(url, str);
            System.out.println(soapResponse);
        } catch (ConnectTimeoutException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}