First, introduce some good websites:
Introduction to httpclient: http://www.ibm.com/developerworks/cn/opensource/os-httpclient/
HTTP client certificate import: http://www.blogjava.net/happytian/archive/2006/12/22/89447.html
Advanced knowledge of httpclient: http://laohuang.iteye.com/blog/55613
HTTP client official document: http://hc.apache.org/http components-client/index.html
HTTP client resource closure: http://www.iteye.com/topic/234759
Examples: http://blog.csdn.net/z69183787/article/details/19153369
And then, that's the sentence... Good things to reproduce, learn one can not be less, below Turn from here
I believe that the importance of the Http protocol does not need to say much. Compared with the URLConnection provided by traditional JDK, HttpClient adds ease of use and flexibility (specific differences, we will discuss later). It is not only easier for clients to send Http requests, but also for developers. test Interface (based on Http protocol) improves the efficiency of development and the robustness of code. Therefore, mastering HttpClient is a very important required content. After mastering HttpClient, I believe that the understanding of Http protocol will be more in-depth.
I. IntroductionHttpClient is a sub-project of Apache Jakarta Common. It provides an efficient, up-to-date and feature-rich client programming toolkit to support HTTP protocol, and it supports the latest version and recommendations of HTTP protocol. HttpClient has been used in many projects, such as Apache Jakarta and two other well-known open source projects, Cactus and HTMLUnit, which use HttpClient.
Download address: http://hc.apache.org/downloads.cgi
Two, characteristics1. Standard-based, pure Java Language. Implementation of Http1.0 and Http1.1
2. All methods of Http (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) are implemented with extensible object-oriented structure.
3. Support HTTPS protocol.
4. Establish transparent connections through Http proxy.
5. Use CONNECT method to establish tunnel https connection through Http proxy.
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos authentication scheme.
7. Plug-in custom authentication scheme.
8. Portable and reliable socket factories make it easier to use third-party solutions.
9. Connection Manager supports multi-threaded applications. Supports setting the maximum number of connections, and also supports setting the maximum number of connections per host, discovering and closing outdated connections.
10. Automatically process Cookies in Set-Cookie.
11. Plug-in custom Cookie policy.
12. Request's output stream prevents content from being buffered directly to the socket server.
13. Response's input stream can effectively read the corresponding content directly from the socket server.
14. KeepAlive is used to maintain persistent connections in HTTP 1.0 and HTTP 1.1.
15. Get the response code and headers sent by the server directly.
16. Set the connection timeout capability.
17. Experimental support http1.1 response caching.
18. The source code is freely available based on Apache License.
Using HttpClient to send requests and receive responses is very simple. Generally, the following steps are needed.
1. Create the HttpClient object.
2. Create an instance of the request method and specify the request URL. If you need to send a GET request, create the HttpGet object; if you need to send a POST request, create the HttpPost object.
3. If you need to send request parameters, you can call HttpGet and HttpPost common setParams(HetpParams params) method to add request parameters; for HttpPost objects, you can also call setEntity(HttpEntity entity) method to set request parameters.
4. Call the execute(HttpUriRequest request) of the HttpClient object to send the request, which returns a HttpResponse.
5. The server's response header can be obtained by calling the getAllHeaders(), getHeaders(String name) of HttpResponse, and the HttpResponse's getEntity() method can be used to obtain the HttpEntity object, which wraps the server's response content. The program can get the response content of the server through this object.
6. Release the connection. Whether or not the execution method succeeds, the connection must be released
Four. Example
- public class HttpClientTest {
- @Test
- public void jUnitTest() {
- get();
- }
- /**
- * HttpClient Connect SSL
- */
- public void ssl() {
- CloseableHttpClient httpclient = null;
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
- try {
- //Load keyStore d:\tomcat.keystore
- trustStore.load(instream, "123456".toCharArray());
- } catch (CertificateException e) {
- e.printStackTrace();
- } finally {
- try {
- instream.close();
- } catch (Exception ignore) {
- }
- }
- //Believe in your CA and all self-signed certificates
- SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
- //Only TLSv1 protocol is allowed
- SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
- SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
- httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
- //Create http requests (get mode)
- HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
- System.out.println("executing request" + httpget.getRequestLine());
- CloseableHttpResponse response = httpclient.execute(httpget);
- try {
- HttpEntity entity = response.getEntity();
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- if (entity != null) {
- System.out.println("Response content length: " + entity.getContentLength());
- System.out.println(EntityUtils.toString(entity));
- EntityUtils.consume(entity);
- }
- } finally {
- response.close();
- }
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (KeyManagementException e) {
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- } catch (KeyStoreException e) {
- e.printStackTrace();
- } finally {
- if (httpclient != null) {
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * post Form submission (simulated user login request)
- */
- public void postForm() {
- //Create a default httpClient instance.
- CloseableHttpClient httpclient = HttpClients.createDefault();
- //Create httppost
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
- //Create parameter queues
- List<namevaluepair> formparams = new ArrayList<namevaluepair>();
- formparams.add(new BasicNameValuePair("username", "admin"));
- formparams.add(new BasicNameValuePair("password", "123456"));
- UrlEncodedFormEntity uefEntity;
- try {
- uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httppost.setEntity(uefEntity);
- System.out.println("executing request " + httppost.getURI());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- System.out.println("--------------------------------------");
- System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
- System.out.println("--------------------------------------");
- }
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- //Close the connection and release resources
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Send a post request to access the local application and return different results depending on the passing parameters
- */
- public void post() {
- //Create a default httpClient instance.
- CloseableHttpClient httpclient = HttpClients.createDefault();
- //Create httppost
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
- //Create parameter queues
- List<namevaluepair> formparams = new ArrayList<namevaluepair>();
- formparams.add(new BasicNameValuePair("type", "house"));
- UrlEncodedFormEntity uefEntity;
- try {
- uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httppost.setEntity(uefEntity);
- System.out.println("executing request " + httppost.getURI());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- System.out.println("--------------------------------------");
- System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
- System.out.println("--------------------------------------");
- }
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- //Close the connection and release resources.
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Send get request
- */
- public void get() {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- //Create httpget.
- HttpGet httpget = new HttpGet("http://www.baidu.com/");
- System.out.println("executing request " + httpget.getURI());
- //Execute get requests.
- CloseableHttpResponse response = httpclient.execute(httpget);
- try {
- //Getting response entities
- HttpEntity entity = response.getEntity();
- System.out.println("--------------------------------------");
- //Print response status
- System.out.println(response.getStatusLine());
- if (entity != null) {
- //Print response content length
- System.out.println("Response content length: " + entity.getContentLength());
- //Print response content
- System.out.println("Response content: " + EntityUtils.toString(entity));
- }
- System.out.println("------------------------------------");
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- //Close the connection and release resources.
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Upload files
- */
- public void upload() {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
- FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
- StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
- HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
- httppost.setEntity(reqEntity);
- System.out.println("executing request " + httppost.getRequestLine());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- HttpEntity resEntity = response.getEntity();
- if (resEntity != null) {
- System.out.println("Response content length: " + resEntity.getContentLength());
- }
- EntityUtils.consume(resEntity);
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }</namevaluepair></namevaluepair></namevaluepair></namevaluepair>
This example uses the latest version of HttpClient 4.3. This version is quite different from the previous code style, we should pay more attention to it.
That's the same sentence... Good things to reproduce, learn one can not be less, below Turn from here
HttpClient has several points to pay attention to in its application:
Where HttpClient is generated:
ttpClient=new HttpClient();
httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
First, you must have the following two parameter settings, otherwise you will generate multiple Cookie header s to the web server
httpClient.getParams().setParameter("http.protocol.single-cookie-header",true);
httpClient.getParams().setParameter("http.protocol.content-charset","gb2312");
ArrayList headerList=new ArrayList();
Header accept=new Header("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-silverlight, */*");
headerList.add(accept);
......
httpClient.getParams().setParameter("http.default-headers",headerList);
httpClient.getParams().setParameter("http.protocol.version",HttpVersion.HTTP_1_1);
httpClient.getParams().setParameter("http.method.retry-handler",new DefaultHttpMethodRetryHandler());
Second: Where httpMethod is generated:
PostMethod postMethod =new PostMethod();
postMethod.getParams().setUriCharset("GB2312");
postMethod.setURI(new URI(url,false,"GB2312"));
client.executeMethod(postMethod);
Above can avoid sending something like "HTTP://127.0.0.1:8080/action.do?" The URI error occurred when the content = 123456 "URL.
Third: The Connection Pool Timeout Exception problem may be caused by several reasons:
1. Setting connection timeout time is not set or too small;
2. Whether the connection after request has been released;
For more information, as well as parameter settings and code writing, risks, see This article