HttpUtils 发送http请求工具类(实例讲解)
废话不多说,直接上代码
importjava.io.IOException; importjava.io.UnsupportedEncodingException; importjava.net.URISyntaxException; importjava.util.ArrayList; importjava.util.Map; importorg.apache.commons.logging.Log; importorg.apache.commons.logging.LogFactory; importorg.apache.http.HttpEntity; importorg.apache.http.NameValuePair; importorg.apache.http.client.ClientProtocolException; importorg.apache.http.client.config.RequestConfig; importorg.apache.http.client.entity.UrlEncodedFormEntity; importorg.apache.http.client.methods.CloseableHttpResponse; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.client.methods.HttpRequestBase; importorg.apache.http.client.utils.URIBuilder; importorg.apache.http.entity.StringEntity; importorg.apache.http.impl.client.CloseableHttpClient; importorg.apache.http.impl.client.HttpClients; importorg.apache.http.impl.conn.PoolingHttpClientConnectionManager; importorg.apache.http.message.BasicNameValuePair; importorg.apache.http.util.EntityUtils; importcom.pingan.qhcs.map.audit.constant.CodeConstant; importcom.pingan.qhcs.map.audit.exception.MapException; publicclassHttpClientUtil{ protectedstaticLoglogger=LogFactory.getLog(HttpClientUtil.class); privatestaticPoolingHttpClientConnectionManagercm; privatestaticStringEMPTY_STR=""; privatestaticStringUTF_8="UTF-8"; privatestaticvoidinit(){ if(cm==null){ cm=newPoolingHttpClientConnectionManager(); cm.setMaxTotal(50);//整个连接池最大连接数 cm.setDefaultMaxPerRoute(5);//每路由最大连接数,默认值是2 } } /** *通过连接池获取HttpClient * *@return */ publicstaticCloseableHttpClientgetHttpClient(){ init(); returnHttpClients.custom().setConnectionManager(cm).build(); } publicstaticStringhttpGetRequest(Stringurl){ HttpGethttpGet=newHttpGet(url); returngetResult(httpGet); } publicstaticStringhttpGetRequest(Stringurl,Mapparams)throwsURISyntaxException{ URIBuilderub=newURIBuilder(); ub.setPath(url); ArrayList pairs=covertParams2NVPS(params); ub.setParameters(pairs); HttpGethttpGet=newHttpGet(ub.build()); returngetResult(httpGet); } publicstaticStringhttpGetRequest(Stringurl,Map headers,Map params) throwsURISyntaxException{ URIBuilderub=newURIBuilder(); ub.setPath(url); ArrayList pairs=covertParams2NVPS(params); ub.setParameters(pairs); HttpGethttpGet=newHttpGet(ub.build()); for(Map.Entry param:headers.entrySet()){ httpGet.addHeader(param.getKey(),String.valueOf(param.getValue())); } returngetResult(httpGet); } publicstaticStringhttpPostRequest(Stringurl){ HttpPosthttpPost=newHttpPost(url); returngetResult(httpPost); } publicstaticStringhttpPostRequest(Stringurl,Map params)throwsUnsupportedEncodingException{ HttpPosthttpPost=newHttpPost(url); ArrayList pairs=covertParams2NVPS(params); httpPost.setEntity(newUrlEncodedFormEntity(pairs,UTF_8)); returngetResult(httpPost); } publicstaticStringhttpPostRequest(Stringurl,Map headers,Map params) throwsUnsupportedEncodingException{ HttpPosthttpPost=newHttpPost(url); for(Map.Entry param:headers.entrySet()){ httpPost.addHeader(param.getKey(),String.valueOf(param.getValue())); } ArrayList pairs=covertParams2NVPS(params); httpPost.setEntity(newUrlEncodedFormEntity(pairs,UTF_8)); returngetResult(httpPost); } publicstaticStringhttpPostRequest(Stringurl,Map headers,StringstrBody) throwsException{ HttpPosthttpPost=newHttpPost(url); for(Map.Entry param:headers.entrySet()){ httpPost.addHeader(param.getKey(),String.valueOf(param.getValue())); } httpPost.setEntity(newStringEntity(strBody,UTF_8)); returngetResult(httpPost); } privatestaticArrayList covertParams2NVPS(Map params){ ArrayList pairs=newArrayList (); for(Map.Entry param:params.entrySet()){ pairs.add(newBasicNameValuePair(param.getKey(),String.valueOf(param.getValue()))); } returnpairs; } /** *处理Http请求 * *setConnectTimeout:设置连接超时时间,单位毫秒。 *setConnectionRequestTimeout:设置从connectManager获取Connection超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。 *setSocketTimeout:请求获取数据的超时时间,单位毫秒。如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 * *@paramrequest *@return */ privatestaticStringgetResult(HttpRequestBaserequest){ RequestConfigrequestConfig=RequestConfig.custom().setConnectTimeout(60000) .setConnectionRequestTimeout(5000).setSocketTimeout(60000).build(); request.setConfig(requestConfig);//设置请求和传输超时时间 //CloseableHttpClienthttpClient=HttpClients.createDefault(); CloseableHttpClienthttpClient=getHttpClient(); try{ CloseableHttpResponseresponse=httpClient.execute(request);//执行请求 //response.getStatusLine().getStatusCode(); HttpEntityentity=response.getEntity(); if(entity!=null){ //longlen=entity.getContentLength();//-1表示长度未知 Stringresult=EntityUtils.toString(entity); response.close(); //httpClient.close(); returnresult; } }catch(ClientProtocolExceptione){ logger.error("[maperror]HttpClientUtilClientProtocolException:"+e.getMessage()); thrownewMapException(CodeConstant.CODE_CONNECT_FAIL,"HttpClientUtilClientProtocolException:"+e.getMessage()); }catch(IOExceptione){ logger.error("[maperror]HttpClientUtilIOException:"+e.getMessage()); thrownewMapException(CodeConstant.CODE_CONNECT_FAIL,"HttpClientUtilIOException:"+e.getMessage()); }finally{ } returnEMPTY_STR; } }
以上这篇HttpUtils发送http请求工具类(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。