Use of HttpClient

Source: Internet
Author: User

HTTP protocol may be the most widely used and important protocol on the Internet. More and more Java applications need to directly access network resources through HTTP protocol.
The main functions of http include:
1. implemented all HTTP methods (GET, POST, PUT, HEAD, etc)
2. Support for automatic steering
3. Support for HTTPS
4. Support for proxy servers
The following six steps are required to use HttpClient:
1. Create an HttpClient instance
2. Create an instance of a certain connection method. Here is GetMethod. Input the address to be connected in the GetMethod constructor.
3. Call the execute method of the Instance created in step 1 to execute the method Instance created in step 2.
4. Read response
5. Release the connection. The connection must be released no matter whether the execution method is successful or not.
6. process the obtained content
 
Based on the above steps, we will compile the code that uses the GET method to obtain the content of a webpage.
In most cases, the default HttpClient constructor is sufficient.
HttpClient httpClient = new HttpClient ();
Create an instance of the GET method. Enter the address to be connected in the GET method constructor. GetMethod will automatically process the forwarding process. If you want to remove the automatic forwarding process, you can call setFollowRedirects (false ).
GetMethod getMethod = new GetMethod (http://www.ibm.com /);
Call the executeMethod method of the Instance httpClient to execute getMethod. Because it is a program executed on the network, when running the executeMethod method, you need to handle two exceptions: HttpException and IOException. The first exception may be caused by incorrect input protocol when getMethod is constructed, for example, accidentally writing "http" into "htp", or abnormal content returned by the server, this exception is irrecoverable. The second exception is generally caused by network issues. For this exception (IOException ), httpClient automatically tries to re-execute the executeMethod Method Based on the recovery policy you specified. The restoration policy of HttpClient can be customized (implemented through the implementation interface HttpMethodRetryHandler ). Use the httpClient method setParameter to set your implemented recovery policy. This document uses the default recovery policy provided by the system. This policy will automatically retry three times when a second type of exception occurs. The returned result of executeMethod is an integer that indicates the status code returned by the server after the method is executed, the status code indicates whether the method is successfully executed, whether authentication is required, or whether the page jumps. By default, the GetMethod instance automatically handles the jumps.
 
Java code
// Set the default recovery policy. When an exception occurs, the system automatically retries three times. Here, you can set a custom recovery policy.
GetMethod. getParams (). setParameter (HttpMethodParams. RETRY_HANDLER,
New DefaultHttpMethodRetryHandler ());
// Execute getMethod
Int statusCode = client.exe cuteMethod (getMethod );
If (statusCode! = HttpStatus. SC _ OK ){
System. err. println ("Method failed:" + getMethod. getStatusLine ());
}
// Set the default recovery policy. When an exception occurs, the system automatically retries three times. Here, you can set a custom recovery policy.
GetMethod. getParams (). setParameter (HttpMethodParams. RETRY_HANDLER,
New DefaultHttpMethodRetryHandler ());
// Execute getMethod
Int statusCode = client.exe cuteMethod (getMethod );
If (statusCode! = HttpStatus. SC _ OK ){
System. err. println ("Method failed:" + getMethod. getStatusLine ());
}

 
After the returned status code is correct, you can obtain the content. There are three methods to get the content of the target address: first, getResponseBody, which returns the binary byte stream of the target; second, getResponseBodyAsString, which returns the String type, it is worth noting that the String returned by this method is encoded according to the system's default encoding method, so the returned String value may have an incorrect encoding type, this is described in detail in the "character encoding" section. The third is getResponseBodyAsStream, which is the best method for transmitting a large amount of data in the target address. Here we use the simplest getResponseBody method.
Release the connection. The connection must be released no matter whether the execution method is successful or not.
Method. releaseConnection ();

Processing content. In this step, content is processed according to your needs. In this example, the content is simply printed to the console.
System. out. println (new String (responseBody ));

Complete code example
Java code
Public class FeedBackServiceImpl implements FeedBackService, InitializingBean {
Private static final Logger log = LoggerFactory. getLogger (FeedBackServiceImpl. class );
 
Private static final int CONNECTION_TIME_OUT = 1000;
Private static final int TIME_OUT = 2000;
/**
* Parameters
*/
Private static final String PARAM_ID = "id ";
Private static final String PARAM_QUESTION_ID = "questionId ";
Private static final String PARAM_ANSWER = "answer ";
Private static final String PARAM_COOKIE_ID = "cookieId ";
 
/**
* The Gaya system obtains the url of the questionnaire.
*/
Private String feedBackQuestionaireUrl;
/**
* The Gaya system saves the url of user feedback.
*/
Private String feedBackAnswerUrl;
/**
* Ing between the questionnaire type and the questionnaire id
*
* <Pre>
* The questionnaire type is transmitted from the front-end. Currently, two values are available: "1" indicates the questionnaire on the purchase order page; "2" indicates the questionnaire on the order confirmation page.
* Questionnaire id, used as a parameter to obtain the questionnaire from the geya System
* </Pre>
*/
Private Map <String, String> questionTypeToQuestionId = new HashMap <String, String> ();
 
Private HttpClient httpClient;
 
Public boolean addFeedBack (FeedBackModel feedBackModel ){
If (feedBackModel = null ){
Return false;
}
Boolean res = false;
// Call the interface of the Gaya system to Submit Feedback
PostMethod postMethod = new PostMethod (feedBackAnswerUrl );
PostMethod. addParameter (PARAM_QUESTION_ID, feedBackModel. getQuestionId ());
PostMethod. addParameter (PARAM_ANSWER, feedBackModel. getAnswer ());
PostMethod. addParameter (PARAM_COOKIE_ID, feedBackModel. getCookieId ());
Try {
Int statusCode = httpClient.exe cuteMethod (postMethod );
If (statusCode! = HttpStatus. SC _ OK ){
StringBuilder sb = new StringBuilder ("fail to add feedback, requestUrl = ");
Sb. append (feedBackAnswerUrl). append (", parameter:"). append (feedBackModel. toString (). append (", HTTP StatusCode ="). append (statusCode );
Log. error (sb. toString ());
Res = false;
} Else {
Res = true;
}
} Catch (HttpException e ){
Log. error ("HttpException occured when addFeedBack, requestUrl =" + feedBackAnswerUrl + ", parameter:" + feedBackModel. toString (), e );
Res = false;
} Catch (IOException e ){
Log. error ("IOException occured when addFeedBack, requestUrl =" + feedBackAnswerUrl + ", parameter:" + feedBackModel. toString (), e );
Res = false;
} Finally {
PostMethod. releaseConnection ();
PostMethod = null;
}
Return res;
}
 
Public JSONObject getQuestionaire (String questionType ){
String id = questionTypeToQuestionId. get (questionType );
If (StringUtil. isBlank (id )){
Return null;
}

// Call the interface of the Gaya system to obtain the questionnaire
GetMethod getMethod = new GetMethod (feedBackQuestionaireUrl );
NameValuePair param = new NameValuePair (PARAM_ID, id );
GetMethod. setQueryString (new NameValuePair [] {param });
String responseText = null;
Try {
// Execute getMethod
Int statusCode = httpClient.exe cuteMethod (getMethod );
If (statusCode! = HttpStatus. SC _ OK ){
StringBuilder sb = new StringBuilder ("fail to getQuestionaire, requestUrl = ");
Sb. append (feedBackQuestionaireUrl). append ("? Id = "). append (id). append (", HTTP StatusCode = "). append (statusCode );
Log. error (sb. toString ());
Return null;
}
// Read content
ResponseText = getMethod. getResponseBodyAsString ();
} Catch (HttpException e ){
StringBuilder sb = new StringBuilder ("HttpException occured when getQuestionaire, requestUrl = ");
Sb. append (feedBackQuestionaireUrl). append ("? Id = "). append (id );
Log. error (sb. toString (), e );
Return null;
} Catch (IOException e ){
StringBuilder sb = new StringBuilder ("IOException occured when getQuestionaire, requestUrl = ");
Sb. append (feedBackQuestionaireUrl). append ("? Id = "). append (id );
Log. error (sb. toString (), e );
Return null;
} Finally {
GetMethod. releaseConnection ();
GetMethod = null;
}

If (StringUtil. isBlank (responseText )){
Return null;
}

// Parse the json string containing the questionnaire from the query result
Int index = responseText. indexOf ("= ");
If (index> = 0 ){
ResponseText = responseText. substring (index + 1 );
}
Try {
JSONObject json = JSONObject. fromObject (responseText );
Return json;
} Catch (Exception e ){
Log. error ("fail to change from String to JSONObject, string =" + responseText, e );
Return null;
}
}

Public void afterPropertiesSet () throws Exception {
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager ();
HttpClient = new HttpClient (connectionManager );
HttpClient. setConnectionTimeout (CONNECTION_TIME_OUT );
HttpClient. setTimeout (TIME_OUT );
}

Author "hwy584624785"
 

Related Article

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.