Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the HttpClient 4.0wrapper utility class?

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how the HttpClient 4.0 encapsulation tool class is, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

The following is the HttpClient tool class encapsulated by me in the actual development process, HttpClient 4 changes greatly compared to HttpClient 3, especially in SSL, the package structure has been changed beyond recognition, but the use of HttpClient 4 SSL and digital certificate two-way authentication is more clear and simple. [@ more@]

/ *

* @ {#} HttpclientUtil.java

*

* Pingzonglangji.com Inc.

*

* Copyright (c) 2008-2009 All Rights Reserved.

, /

Package com.pingzonglangji.common.net

Import java.io.FileNotFoundException

Import java.io.IOException

Import java.io.InputStream

Import java.io.UnsupportedEncodingException

Import java.net.URL

Import java.security.KeyManagementException

Import java.security.KeyStore

Import java.security.KeyStoreException

Import java.security.NoSuchAlgorithmException

Import java.security.UnrecoverableKeyException

Import java.security.cert.CertificateException

Import java.util.ArrayList

Import java.util.List

Import java.util.Map

Import javax.net.ssl.SSLHandshakeException

Import org.apache.http.HttpEntity

Import org.apache.http.HttpEntityEnclosingRequest

Import org.apache.http.HttpException

Import org.apache.http.HttpRequest

Import org.apache.http.HttpResponse

Import org.apache.http.HttpVersion

Import org.apache.http.NameValuePair

Import org.apache.http.NoHttpResponseException

Import org.apache.http.client.ClientProtocolException

Import org.apache.http.client.HttpClient

Import org.apache.http.client.HttpRequestRetryHandler

Import org.apache.http.HttpRequestInterceptor

Import org.apache.http.client.ResponseHandler

Import org.apache.http.client.entity.UrlEncodedFormEntity

Import org.apache.http.client.methods.HttpGet

Import org.apache.http.client.methods.HttpPost

Import org.apache.http.client.methods.HttpRequestBase

Import org.apache.http.client.utils.URLEncodedUtils

Import org.apache.http.conn.scheme.Scheme

Import org.apache.http.conn.ssl.SSLSocketFactory

Import org.apache.http.impl.client.DefaultHttpClient

Import org.apache.http.message.BasicNameValuePair

Import org.apache.http.params.CoreProtocolPNames

Import org.apache.http.protocol.ExecutionContext

Import org.apache.http.protocol.HttpContext

Import org.apache.http.util.EntityUtils

Import com.pingzonglangji.common.lang.StringUtil

/ * *

* Apache Httpclient 4.0tool wrapper class

*

* @ author shezy

, /

@ SuppressWarnings ("all")

Public class HttpclientUtil {

Private static final String CHARSET_UTF8 = "UTF-8"

Private static final String CHARSET_GBK = "GBK"

Private static final String SSL_DEFAULT_SCHEME = "https"

Private static final int SSL_DEFAULT_PORT = 443

/ / automatic exception recovery handling, using HttpRequestRetryHandler API to realize the exception recovery of the request

Private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler () {

/ / Custom recovery policy

Public boolean retryRequest (IOException exception, int executionCount, HttpContext context) {

/ / set the recovery policy and automatically retry 3 times when an exception occurs.

If (executionCount > = 3) {

/ / Do not retry if over max retry count

Return false

}

If (exception instanceof NoHttpResponseException) {

/ / Retry if the server dropped connection on us

Return true

}

If (exception instanceof SSLHandshakeException) {

/ / Do not retry on SSL handshake exception

Return false

}

HttpRequest request = (HttpRequest) context.getAttribute (ExecutionContext.HTTP_REQUEST)

Boolean idempotent = (request instanceof HttpEntityEnclosingRequest)

If (! idempotent) {

/ / Retry if the request is considered idempotent

Return true

}

Return false

}

}

/ / ResponseHandler API is used to process the response. HttpClient uses ResponseHandler to automatically manage the release of the connection, which solves the problem of the release management of the connection.

Private static ResponseHandlerresponseHandler = new ResponseHandler () {

/ / Custom response handling

Public String handleResponse (HttpResponse response) throws ClientProtocolException, IOException {

HttpEntity entity = response.getEntity ()

If (entity! = null) {

String charset = EntityUtils.getContentCharSet (entity) = = null? CHARSET_GBK: EntityUtils.getContentCharSet (entity)

Return new String (EntityUtils.toByteArray (entity), charset)

} else {

Return null

}

}

}

/ * *

* submit by Get. Query parameters are included in URL. Format: http://www.g.cn?search=p&name=s......

*

* @ param url

* submit address

* @ return response message

, /

Public static String get (String url) {

Return get (url, null, null)

}

/ * *

* submit by Get. Query parameters are not included in URL. Format: http://www.g.cn.

*

* @ param url

* submit address

* @ param params

* query parameter sets, key / value pairs

* @ return response message

, /

Public static String get (String url, Mapparams) {

Return get (url, params, null)

}

/ * *

* submit by Get. Query parameters are not included in URL. Format: http://www.g.cn.

*

* @ param url

* submit address

* @ param params

* query parameter sets, key / value pairs

* @ param charset

* Parameter submission code set

* @ return response message

, /

Public static String get (String url, Mapparams, String charset) {

If (url = = null | | StringUtil.isEmpty (url)) {

Return null

}

Listqparams = getParamsList (params)

If (qparams! = null & & qparams.size () > 0) {

Charset = (charset = = null? CHARSET_GBK: charset)

String formatParams = URLEncodedUtils.format (qparams, charset)

Url = (url.indexOf ("?") < 0? Url + "?" + formatParams): (url

.substring (0, url.indexOf ("?") + 1) + formatParams)

}

DefaultHttpClient httpclient = getDefaultHttpClient (charset)

HttpGet hg = new HttpGet (url)

/ / send a request and get a response

String responseStr = null

Try {

ResponseStr = httpclient.execute (hg, responseHandler)

} catch (ClientProtocolException e) {

Throw new NetServiceException ("client connection protocol error", e)

} catch (IOException e) {

Throw new NetServiceException ("IO operation exception", e)

} finally {

AbortConnection (hg, httpclient)

}

Return responseStr

}

/ * *

* submit by Post. URL does not contain submission parameters. Format: http://www.g.cn.

*

* @ param url

* submit address

* @ param params

* submit parameter sets, key / value pairs

* @ return response message

, /

Public static String post (String url, Mapparams) {

Return post (url, params, null)

}

/ * *

* submit by Post. URL does not contain submission parameters. Format: http://www.g.cn.

*

* @ param url

* submit address

* @ param params

* submit parameter sets, key / value pairs

* @ param charset

* Parameter submission code set

* @ return response message

, /

Public static String post (String url, Mapparams, String charset) {

If (url = = null | | StringUtil.isEmpty (url)) {

Return null

}

/ / create a HttpClient instance

DefaultHttpClient httpclient = getDefaultHttpClient (charset)

UrlEncodedFormEntity formEntity = null

Try {

If (charset = = null | | StringUtil.isEmpty (charset)) {

FormEntity = new UrlEncodedFormEntity (getParamsList (params))

} else {

FormEntity = new UrlEncodedFormEntity (getParamsList (params), charset)

}

} catch (UnsupportedEncodingException e) {

Throw new NetServiceException ("unsupported code sets", e)

}

HttpPost hp = new HttpPost (url)

Hp.setEntity (formEntity)

/ / send a request and get a response

String responseStr = null

Try {

ResponseStr = httpclient.execute (hp, responseHandler)

} catch (ClientProtocolException e) {

Throw new NetServiceException ("client connection protocol error", e)

} catch (IOException e) {

Throw new NetServiceException ("IO operation exception", e)

} finally {

AbortConnection (hp, httpclient)

}

Return responseStr

}

/ * *

* submit by Post, ignore the parameters contained in URL and solve the problem of SSL two-way digital certificate authentication

*

* @ param url

* submit address

* @ param params

* submit parameter sets, key / value pairs

* @ param charset

* Parameter coding set

* @ param keystoreUrl

* KeyStore path

* @ param keystorePassword

* KeyStore access password

* @ param truststoreUrl

* Trust Store absolute path

* @ param truststorePassword

* truststore access password, which can be null

* @ return response message

* @ throws NetServiceException

, /

Public static String post (String url, Mapparams, String charset, final URL keystoreUrl

Final String keystorePassword, final URL truststoreUrl,final String truststorePassword) {

If (url = = null | | StringUtil.isEmpty (url)) {

Return null

}

DefaultHttpClient httpclient = getDefaultHttpClient (charset)

UrlEncodedFormEntity formEntity = null

Try {

If (charset = = null | | StringUtil.isEmpty (charset)) {

FormEntity = new UrlEncodedFormEntity (getParamsList (params))

} else {

FormEntity = new UrlEncodedFormEntity (getParamsList (params), charset)

}

} catch (UnsupportedEncodingException e) {

Throw new NetServiceException ("unsupported code sets", e)

}

HttpPost hp = null

String responseStr = null

Try {

KeyStore keyStore = createKeyStore (keystoreUrl, keystorePassword)

KeyStore trustStore = createKeyStore (truststoreUrl, keystorePassword)

SSLSocketFactory socketFactory = new SSLSocketFactory (keyStore,keystorePassword, trustStore)

Scheme scheme = new Scheme (SSL_DEFAULT_SCHEME, socketFactory, SSL_DEFAULT_PORT)

Httpclient.getConnectionManager (). GetSchemeRegistry (). Register (scheme)

Hp = new HttpPost (url)

Hp.setEntity (formEntity)

ResponseStr = httpclient.execute (hp, responseHandler)

} catch (NoSuchAlgorithmException e) {

Throw new NetServiceException ("specified encryption algorithm is not available", e)

} catch (KeyStoreException e) {

Throw new NetServiceException ("keytore parsing exception", e)

} catch (CertificateException e) {

Throw new NetServiceException ("trust certificate expired or resolution exception", e)

} catch (FileNotFoundException e) {

Throw new NetServiceException ("keystore file does not exist", e)

} catch (IOException e) {

Throw new NetServiceException ("Icano operation failed or interrupted", e)

} catch (UnrecoverableKeyException e) {

Throw new NetServiceException ("keys in keystore cannot recover exceptions", e)

} catch (KeyManagementException e) {

Throw new NetServiceException ("handling operation exceptions for key management", e)

} finally {

AbortConnection (hp, httpclient)

}

Return responseStr

}

/ * *

* obtain DefaultHttpClient instance

*

* @ param charset

* Parameter coding set, nullable

* @ return DefaultHttpClient object

, /

Private static DefaultHttpClient getDefaultHttpClient (final String charset) {

DefaultHttpClient httpclient = new DefaultHttpClient ()

Httpclient.getParams () .setParameter (CoreProtocolPNames.PROTOCOL_VERSION HttpVersion.HTTP_1_1)

/ / simulate browsers to solve the problem that some server programs only allow browsers to access

Httpclient.getParams () .setParameter (CoreProtocolPNames.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)")

Httpclient.getParams () .setParameter (CoreProtocolPNames.USE_EXPECT_CONTINUE Boolean.FALSE)

Httpclient.getParams () .setParameter (CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset = = null? CHARSET_GBK: charset)

Httpclient.setHttpRequestRetryHandler (requestRetryHandler)

Return httpclient

}

/ * *

* release HttpClient connection

*

* @ param hrb

* request object

* @ param httpclient

* client object

, /

Private static void abortConnection (final HttpRequestBase hrb, final HttpClient httpclient) {

If (hrb! = null) {

Hrb.abort ()

}

If (httpclient! = null) {

Httpclient.getConnectionManager () .shutdown ()

}

}

/ * *

* load this KeyStore from the given path

*

* @ param url

* keystore URL path

* @ param password

* keystore access key

* @ return keystore object

, /

Private static KeyStore createKeyStore (final URL url, final String password)

Throws KeyStoreException, NoSuchAlgorithmException,CertificateException, IOException {

If (url = = null) {

Throw new IllegalArgumentException ("Keystore url may not be null")

}

KeyStore keystore = KeyStore.getInstance (KeyStore.getDefaultType ())

InputStream is = null

Try {

Is = url.openStream ()

Keystore.load (is, password! = null? Password.toCharArray (): null)

} finally {

If (is! = null) {

Is.close ()

Is = null

}

}

Return keystore

}

/ * *

* convert the passed key / value pair parameters to the NameValuePair parameter set

*

* @ param paramsMap

* Parameter set, key / value pair

* @ return NameValuePair parameter set

, /

Private static ListgetParamsList (MapparamsMap) {

If (paramsMap = = null | | paramsMap.size () = = 0) {

Return null

}

Listparams = new ArrayList ()

For (Map.Entrymap: paramsMap.entrySet ()) {

Params.add (new BasicNameValuePair (map.getKey (), map.getValue ()

}

Return params

}

}

About HttpClient 4.0 encapsulation tool class is how to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report