Apache HttpClient4.5 (i) __java improved

Source: Internet
Author: User
Tags html form keep alive
To create an HTTP client
Closeablehttpclient httpclient = Httpclientbuilder.create (). build ();
You can also configure the requested parameter for the client, as the default value for all requests
requestconfig requestconfig = Requestconfig.custom ()
        . Setconnectionrequesttimeout (5000)
        . Setconnecttimeout (5000).
        setsockettimeout (5000)
        . Setcookiespec ( Cookiespecs.default)
        . Build ();
Closeablehttpclient httpclient = Httpclients.custom ()
        . Setdefaultrequestconfig (Requestconfig)
        . Build ();
Create a GET request
HttpGet httpget = new HttpGet ("Http://localhost/index.html?param1=value1¶m2=value2");
HttpClient provides UriBuilder tool classes to simplify the creation of URIs
URI uri = null;
try {
    uri= new UriBuilder ()
            . SetScheme ("http")
            . Sethost ("localhost").
            SetPath ("/index.html"
            ) . Setparameter ("param1", "value1")
            . Setparameter ("param2", "value2")
            . Build ();
URISyntaxException e) {
    e.printstacktrace ();
}
HttpGet httpget = new HttpGet (URI);
If the parameter contains Chinese, you need to urlencoding the parameters
URI uri = null;
try {
    uri = new UriBuilder ()
            . SetScheme ("http")
            . Sethost ("localhost").
            SetPath ("/index.html")
            . Setparameter ("param1", Urlencoder.encode ("China", "UTF-8"))
            . Setparameter ("param2", "value2")
            . Build ();
} catch (Unsupportedencodingexception | URISyntaxException e) {
    e.printstacktrace ();
}
HttpGet httpget = new HttpGet (URI);
You can set some configuration for a single request
Httpget.setconfig (Requestconfig.default);
Create POST request
HttpPost HttpPost = new HttpPost ("http://www.baidu.com");
The HttpPost URI and Requestconfig settings are the same as HttpGet. Message headers can be set for HttpGet and HttpPost
Httppost.addheader (Httpheaders.content_type, "Application/octet-stream;charset=utf-8");
Httpget.addheader (httpheaders.accept, "application/xml");
Execute Request
Closeablehttpresponse response = null;
try {
    response = Httpclient.execute (httpget);
    Gets the status code int status
    = Response.getstatusline () of the HTTP response. Getstatuscode ();
    SYSTEM.OUT.PRINTLN (status);
catch (IOException e) {
    e.printstacktrace ();
} finally {
    try {
        if (response!= null) Response.close () ;
    } catch (IOException e) {
        e.printstacktrace ();
    }
}
Closeablehttpresponse response = null;
try {
    Closeablehttpresponse response = Httpclient.execute (httppost);
    System.out.println (Response.getstatusline ());
    System.out.println (Response.getallheaders ());
    SYSTEM.OUT.PRINTLN (response. Getheaders (Httpheaders.content_type);
    System.out.println (Response.getentity ());
} catch (IOException e) {
    e.printstacktrace ();
} finally {
    try {
        if (response!= null) response.close (); c11/>} catch (IOException e) {
        e.printstacktrace ();
    }
}
using httpentity
When an HTTP request or HTTP request that executes a complete content is successful, the HTTP entity is created when the server sends a response to the client. Httpentity can be obtained by using the GetEntity () method of the HttpResponse, and the GetContent method of the Httpentity class can be used to obtain the input stream (Java.io.InputStream) of the entity. Alternatively, the WriteTo (OutputStream) method of the Httpentity class is used to obtain the output stream, which writes all content to a given stream or uses entityutils.
Gets the response of the httpentity
httpentity entity = response.getentity ();
Header type = Entity.getcontenttype ();//content-type
Long length = Entity.getcontentlength ();//content-length
Header encoding = entity.getcontentencoding ();

Gets the media type of the response, for example: text/html
String contentmimetype = Contenttype.getordefault (entity). GetMimeType ();

Gets the body part of the response
String bodyasstring = entityutils.tostring (entity);
InputStream instream = Entity.getcontent ();
try {
    //do something useful  
} finally {
    instream.close ();
}
In some cases, you want to be able to read the contents of the HTTP entity repeatedly. This requires the HTTP entity content to be cached on memory or on disk. The easiest way to do this is to convert the HTTP entity into bufferedhttpentity, which buffers the contents of the original HTTP entity into memory. The contents of the bufferedhttpentity can be read repeatedly later.
httpentity entity = response.getentity ();  
if (entity!= null) {  
    entity = new bufferedhttpentity (entity);  
}
simulate submitting an HTML form request
HttpPost HttpPost = new HttpPost ("http://www.baidu.com");

Splicing parameters
list<namevaluepair> formparams = new arraylist<> ();
Formparams.add (New Basicnamevaluepair ("username", "VIP"));
Formparams.add (New Basicnamevaluepair ("Password", "secret"));
urlencodedformentity entity = new Urlencodedformentity (Formparams, consts.utf_8);
Httppost.setentity (entity);
Send binary
Httppost.addheader ("Content-type", "Application/octet-stream;charset=utf-8");
Httppost.setentity (New Bytearrayentity (bytes));
ResponseHandler
The simplest and easiest way to handle HTTP responses is to use the ResponseHandler interface, which has the Handleresponse (HttpResponse response) method. With this method, the user does not have to care about the HTTP Connection manager at all. When ResponseHandler is used, HttpClient automatically releases the HTTP connection to the HTTP manager, even if the HTTP request fails or throws an exception.
Closeablehttpclient httpclient = Httpclients.createdefault ();

HttpGet httpget = new HttpGet ("Http://www.yeetrack.com/json"); responsehandler<myjsonobject> RH = new Responsehandler<myjsonobject> () {@Override public jsonobject handle
		Response (final HttpResponse Response) throws IOException {Statusline statusline = Response.getstatusline ();
		httpentity entity = response.getentity (); if (Statusline.getstatuscode () >=) {throw new Httpresponseexception (Statusline.getstatuscode (), stat
		Usline.getreasonphrase ());
		} if (entity = null) {throw new Clientprotocolexception ("Response contains no content");
		} Gson Gson = new Gsonbuilder (). Create ();
		ContentType ContentType = Contenttype.getordefault (entity);
		Charset Charset = Contenttype.getcharset ();
		Reader reader = new InputStreamReader (Entity.getcontent (), CharSet);
	Return Gson.fromjson (reader, Myjsonobject.class);
}
};
Sets the ResponseHandler, and when the HTTP method is executed, the Myjsonobject object is returned. MyjsonobjecT Myjson = Client.execute (HttpGet, RH);
 

HttpClient has been implemented for thread safety. Therefore, when instantiating httpclient, it is also supported for use with multiple requests. When an instance of a closeablehttpclient is no longer in use, and its scope is about to expire, the connection to which it is connected must be closed, and the close () method of the closeablehttpclient can be invoked.
Closeablehttpclient httpclient = Httpclients.createdefault ();
try {
	<...>
} finally {
	//close connection
	httpclient.close ();
}
The HttpClient interface does not specifically restrict and detail the process of HTTP requests, which are implemented separately for connection management, state management, authorization information, and redirection processing. This allows users to more easily expand the functionality of the interface (such as caching response content).
Generally speaking, HttpClient is actually a series of special handler or implementation of the policy interface, these handler (test interfaces) are responsible for dealing with some aspect of HTTP protocol, such as redirect, authentication processing, connection persistence and keep Alive the decision to keep the time. This allows the user to use custom parameters instead of the default configuration to achieve personalized functionality.
Connectionkeepalivestrategy Keepalivestrat = new Defaultconnectionkeepalivestrategy () {
	@Override
	public Long getkeepaliveduration (
		httpresponse Response,
		HttpContext context) {
			long keepAlive = Super.getkeepaliveduration (response, context);
			if (keepAlive = = 1) {
				//If the server does not set keep-alive This parameter, we set it to 5 seconds
				keepAlive = 5000;
			}
			return keepAlive;
	}

;
Customize our own httpclient
closeablehttpclient httpclient = Httpclients.custom ()
		. Setkeepalivestrategy ( Keepalivestrat)
		. Build ();
Reference: http://www.yeetrack.com/?p=779

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.