博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HTTPClient
阅读量:6042 次
发布时间:2019-06-20

本文共 9920 字,大约阅读时间需要 33 分钟。

hot3.png

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
 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
 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();        }    }}

转载于:https://my.oschina.net/reachwang/blog/295784

你可能感兴趣的文章
Tomcat与Web服务器、应用服务器的关系
查看>>
用DFS实现全排列 & 八皇后问题
查看>>
深度学习博客
查看>>
Android总结篇系列:Android Service
查看>>
Android dumpsys命令的使用
查看>>
Linux Kernel系列一:开篇和Kernel启动概要
查看>>
BZOJ 2756: [SCOI2012]奇怪的游戏 网络流/二分
查看>>
master + worker模式的node多核解决框架——node-cluster
查看>>
Android如何实现超级棒的沉浸式体验
查看>>
使用node打造自己的命令行工具方法教程
查看>>
Express代理中间件问题与解决方案
查看>>
||和&&返回什么?
查看>>
linux在文件中查找指定字符串,然后根据查找结果来做进一步的处理
查看>>
在Oracle中删除所有强制性外键约束
查看>>
【R】R语言使用命令行参数 - [编程技巧(Program Skill)]
查看>>
经典算法题每日演练——第二题 五家共井
查看>>
存储过程中拼接的变量和点的问题
查看>>
ASP.NET那点不为人知的事(一)
查看>>
HTML 表格
查看>>
VMware 虚拟化编程(7) — VixDiskLib 虚拟磁盘库详解之三
查看>>