Java Implementation HTTP Request tool class sample _java

Source: Internet
Author: User
Tags getmessage

Returning data through HTTP REST requests

Copy Code code as follows:

Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
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.impl.client.BasicResponseHandler;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

Import java.io.IOException;
Import Java.text.MessageFormat;
Import java.util.List;
Import Java.util.concurrent.TimeUnit;

/**
* A tool class to separate an HTTP request
*
* @author Gu Wei "Guwei" on 14-4-22.3:17
*/
public class Httpclientutils {

private static Final log = Logfactory.getlog (Httpclientutils.class);
/**
* Initialization of HttpClient
*/
private static httpclient httpclient = null;

   /**
     * Production httpclient instance
     * Open, static Factory method, Use to create the monomer
     *
     * @return
     * *
    public static httpclient gethttpclient () {
        if ( HttpClient = = null) {
            httpclient = new Defaulthttpclient (New Threadsafeclientconnmanager ());
       }
        return httpclient;
   }

/**
* Post method call
*
* @param URL
* @param params parameter is a Namevaluepair key value pair Object
* @return Response string
* @throws java.io.UnsupportedEncodingException
*/
public static string Executebypost (string url, list<namevaluepair> params) {
HttpClient httpclient = Gethttpclient ();

HttpPost post = new HttpPost (URL);


responsehandler<string> ResponseHandler = new Basicresponsehandler ();
String Responsejson = null;
try {
if (params!= null) {
Post.setentity (New urlencodedformentity (params));
}
Responsejson = Httpclient.execute (post, ResponseHandler);
Log.info ("httpclient POST request Result:" + Responsejson);
catch (Clientprotocolexception e) {
E.printstacktrace ();
Log.info ("httpclient POST request Exception:" + E.getmessage ());
catch (IOException e) {
E.printstacktrace ();
finally {
Httpclient.getconnectionmanager (). Closeexpiredconnections ();
Httpclient.getconnectionmanager (). Closeidleconnections (Timeunit.seconds);
}
return Responsejson;
}

/**
* Get mode Request
*
* @param url with parameter placeholders, example: Http://****/user/user/center.aspx?_action=getsimpleuserinfo&codes={0}&email={1}
* @param params parameter value array, which needs to correspond to the placeholder order in the URL
* @return Response string
* @throws java.io.UnsupportedEncodingException
*/
public static string Executebyget (String URL, object[] params) {
HttpClient httpclient = Gethttpclient ();

String messages = Messageformat.format (URL, params);

HttpGet get = new HttpGet (messages);

responsehandler<string> ResponseHandler = new Basicresponsehandler ();
String Responsejson = null;
try {
Responsejson = Httpclient.execute (GET, ResponseHandler);
Log.info ("HttpClient GET request Result:" + Responsejson);
catch (Clientprotocolexception e) {
E.printstacktrace ();
Log.info ("HttpClient GET Request Exception:" + E.getmessage ());
catch (IOException e) {
E.printstacktrace ();
Log.info ("HttpClient GET Request Exception:" + E.getmessage ());
finally {
Httpclient.getconnectionmanager (). Closeexpiredconnections ();
Httpclient.getconnectionmanager (). Closeidleconnections (Timeunit.seconds);
}
return Responsejson;
}

/**
* @param URL
* @return
*/
public static string Executebyget (string url) {
HttpClient httpclient = Gethttpclient ();

HttpGet get = new HttpGet (URL);

responsehandler<string> ResponseHandler = new Basicresponsehandler ();
String Responsejson = null;
try {
Responsejson = Httpclient.execute (GET, ResponseHandler);
Log.info ("HttpClient GET request Result:" + Responsejson);
catch (Clientprotocolexception e) {
E.printstacktrace ();
Log.info ("HttpClient GET Request Exception:" + E.getmessage ());
catch (IOException e) {
E.printstacktrace ();
Log.info ("HttpClient GET Request Exception:" + E.getmessage ());
finally {
Httpclient.getconnectionmanager (). Closeexpiredconnections ();
Httpclient.getconnectionmanager (). Closeidleconnections (Timeunit.seconds);
}
return Responsejson;
}
}

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.