apache httclient模式(4.3版本)
public class HttpClientUtils {
public static final int connTimeout= 10000 ;
public static final int readTimeout= 10000 ;
public static final String charset= "UTF-8" ;
private static HttpClient client = null;
private static Logger log = LoggerFactory. getLogger ( HttpClientUtils. class ) ;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager ( ) ;
cm. setMaxTotal ( 128 ) ;
cm. setDefaultMaxPerRoute ( 128 ) ;
client = HttpClients. custom ( ) . setConnectionManager ( cm) . build ( ) ;
}
public static String postMutiPartFormData ( String url, Map< String, String> params) throws Exception {
Map< String, String> headers = new HashMap < > ( ) ;
headers. put ( "Content-type" , "multipart/form-data; charset=utf-8" ) ;
return postMultipartFormData ( url, params, headers, connTimeout, readTimeout) ;
}
public static String postParameters ( String url, Map< String, String> params) throws ConnectTimeoutException,
SocketTimeoutException, Exception {
return postForm ( url, params, null, connTimeout, readTimeout) ;
}
public static String postParameters ( String url, Map< String, String> params, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException,
SocketTimeoutException, Exception {
return postForm ( url, params, null, connTimeout, readTimeout) ;
}
public static String get ( String url) throws Exception {
return get ( url, charset, null, null) ;
}
public static String get ( String url, String charset) throws Exception {
return get ( url, charset, connTimeout, readTimeout) ;
}
public static String post ( String url, String body, String mimeType, String charset, Integer connTimeout, Integer readTimeout)
throws ConnectTimeoutException, SocketTimeoutException, Exception {
HttpClient client = null;
HttpPost post = new HttpPost ( url) ;
String result = "" ;
try {
if ( StringUtils. isNotBlank ( body) ) {
HttpEntity entity = new StringEntity ( body, ContentType. create ( mimeType, charset) ) ;
post. setEntity ( entity) ;
}
Builder customReqConf = RequestConfig. custom ( ) ;
if ( connTimeout != null) {
customReqConf. setConnectTimeout ( connTimeout) ;
}
if ( readTimeout != null) {
customReqConf. setSocketTimeout ( readTimeout) ;
}
post. setConfig ( customReqConf. build ( ) ) ;
HttpResponse res;
if ( url. startsWith ( "https" ) ) {
client = createSSLInsecureClient ( ) ;
res = client. execute ( post) ;
} else {
client = HttpClientUtils. client;
res = client. execute ( post) ;
}
result = EntityUtils. toString ( res. getEntity ( ) , charset) ;