Three ways to implement HTTP requests in Java

Source: Internet
Author: User
Tags readline stringbuffer

At present, the Java implementation of HTTP requests in the most of the two ways: one is through the httpclient of this Third-party open source framework to achieve. HttpClient for HTTP encapsulation is quite good, through it is basically able to meet most of our needs, HttpClient3.1 is org.apache.commons.httpclient under the operation of the Remote URL Toolkit, although no longer updated, However, the implementation of the use of httpClient3.1 code is still many, HttpClient4.5 is org.apache.http.client under the operation of the remote URL of the toolkit, the latest, the other is through the httpurlconnection to achieve, HttpURLConnection is the standard class of Java and is a way to implement Java comparison native.

Oneself in the work three kinds of ways have used, sum up to share to everybody, also convenient oneself later use, words do not say more code.

The first way: Java native httpurlconnection

Package com.powerX.httpClient;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;

public class HttpClient {
public static string Doget (String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
string result = null;//returns the resulting string
try {
To create a remote URL connection object
URL url = new URL (httpurl);
To open a connection through a remote URL connection object, strongly convert to HttpURLConnection class
Connection = (httpurlconnection) url.openconnection ();
Set Connection mode: Get
Connection.setrequestmethod ("get");
To set the timeout for connecting to a host server: 15000 milliseconds
Connection.setconnecttimeout (15000);
Set the time to read remote returned data: 60000 MS
Connection.setreadtimeout (60000);
Send Request
Connection.connect ();
Get the input stream through the connection connection
if (connection.getresponsecode () = = 200) {
is = Connection.getinputstream ();
Encapsulates the input flow is and specifies the character set
br = new BufferedReader (The new InputStreamReader (IS, "UTF-8"));
Storing data
StringBuffer SBF = new StringBuffer ();
String temp = null;
while (temp = Br.readline ())!= null) {
Sbf.append (temp);
Sbf.append ("\ r \ n");
}
result = Sbf.tostring ();
}
catch (Malformedurlexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
finally {
Close Resource
if (null!= BR) {
try {
Br.close ();
catch (IOException e) {
E.printstacktrace ();
}
}

        if (null!= is) {try {is.close ();
            catch (IOException e) {e.printstacktrace ();
} connection.disconnect ();//close remote connection} return result;
    public static string DoPost (string httpurl, string param) {httpurlconnection connection = null;
    InputStream is = null;
    OutputStream OS = null;
    BufferedReader br = null;
    String result = null;
        try {URL url = new URL (httpurl);
        Open connection via remote URL connection connection = (httpurlconnection) url.openconnection ();
        Set connection request mode Connection.setrequestmethod ("POST");
        Setting the connection host Server timeout: 15000 ms Connection.setconnecttimeout (15000);

        Sets the read host server return data timeout time: 60000 Ms Connection.setreadtimeout (60000);
        The default value is: false, which needs to be set to True Connection.setdooutput (true) when transferring data/write data to a remote server;
        The default value is: True, which is set to true when the data is currently read to the remote service, which is optional connection.setdoinput (true); //Format incoming parameters: request parameters should be in the form of name1=value1&name2=value2.
        Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); Set up authentication information: Authorization:bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 connection.setrequestproperty ("Authorization"
        , "bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
        Gets an output stream OS = Connection.getoutputstream () via the Connection object;
        The parameter is written out/transmitted through the output stream object, which is a os.write (Param.getbytes ()) written out by a byte array.
            Gets an input stream from the connection object, and reads the IF (connection.getresponsecode) = = = Connection.getinputstream () to the remote;

            Wrapping an input Stream object: CharSet sets the BR = new BufferedReader (new InputStreamReader (IS, "UTF-8") according to the requirements of the work item group;
            StringBuffer SBF = new StringBuffer ();
            String temp = null;
                Iterate through one line to read data while (temp = Br.readline ())!= null) {sbf.append (temp);
            Sbf.append ("\ r \ n"); result = Sbf.tostriNg ();
    } catch (Malformedurlexception e) {e.printstacktrace ();
    catch (IOException e) {e.printstacktrace ();
            Finally {//close resource if (null!= br) {try {br.close ();
            catch (IOException e) {e.printstacktrace ();
            } if (null!= OS) {try {os.close ();
            catch (IOException e) {e.printstacktrace ();
            } if (null!= is) {try {is.close ();
            catch (IOException e) {e.printstacktrace ();
    }//Disconnect from the remote address URL connection.disconnect ();
return result;
 }

}

The second way: Apache HttpClient3.1

Package com.powerX.httpClient;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import Java.util.Iterator;
Import Java.util.Map;
Import Java.util.Map.Entry;
Import Java.util.Set;

Import Org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
Import org.apache.commons.httpclient.HttpClient;
Import Org.apache.commons.httpclient.HttpStatus;
Import Org.apache.commons.httpclient.NameValuePair;
Import Org.apache.commons.httpclient.methods.GetMethod;
Import Org.apache.commons.httpclient.methods.PostMethod;
Import Org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClient3 {

public static string doget (String URL) {//input stream InputStream is = null;
    BufferedReader br = null;
    String result = null;
    Create HttpClient instance httpclient httpclient = new HttpClient (); To set the HTTP connection Host service timeout: 15000 milliseconds//Get the Connection Manager object, get the Parameter object, and then assign the parameter Httpclient.gethttpconnectionmanager (). Getparams () Setco
    Nnectiontimeout (15000);
    Creates a Get method instance object GetMethod GetMethod = new GetMethod (URL);
    Set a GET request timeout of 60000 milliseconds getmethod.getparams (). Setparameter (Httpmethodparams.so_timeout, 60000); Set request retry mechanism, default retry count: 3 times, Parameter set to TRUE, retry mechanism available, false opposite Getmethod.getparams (). Setparameter (Httpmethodparams.retry_handler
    , New Defaulthttpmethodretryhandler (3, true));
        try {//Execute get method int statusCode = Httpclient.executemethod (GetMethod); To determine if the return code is (StatusCode!= httpstatus.sc_ok) {//If the status code returns not OK, the description fails, and the error message is printed SYSTEM.ERR.PRI
        Ntln ("Method faild:" + getmethod.getstatusline ()); } else {//through GetmeThod instance, gets a remote input stream is = Getmethod.getresponsebodyasstream ();

            Packaging input Stream br = new BufferedReader (new InputStreamReader (IS, "UTF-8"));
            StringBuffer SBF = new StringBuffer ();
            Read the encapsulated input stream String temp = null;
            while (temp = Br.readline ())!= null) {sbf.append (temp). Append ("\ r \ n");
        result = Sbf.tostring ();
    } catch (IOException e) {e.printstacktrace ();
            Finally {//close resource if (null!= br) {try {br.close ();
            catch (IOException e) {e.printstacktrace ();
            } if (null!= is) {try {is.close ();
            catch (IOException e) {e.printstacktrace ();
    }//Release connection getmethod.releaseconnection ();
return result; public static string DoPost (string URL, MAP&LT
    String, object> parammap) {//Get input stream inputstream is = null;
    BufferedReader br = null;
    String result = null;
    Creates a HttpClient instance object httpclient httpclient = new HttpClient (); Set the HttpClient connection host Server timeout: 15000 ms Httpclient.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (15000)
    ;
    Creates a POST Request method instance object Postmethod Postmethod = new Postmethod (URL);

    Sets the POST request Timeout Postmethod.getparams (). Setparameter (Httpmethodparams.so_timeout, 60000);
    namevaluepair[] NVP = null; Determines whether the parameter map collection Parammap is an empty if (null!= parammap && parammap.size () > 0) {//Is not NULL//Create a key-value parameter object array, the size of the parameter
        Number NVP = new namevaluepair[parammap.size ()];
        Loop traversal parameter set map set<entry<string, object>> entryset = Parammap.entryset ();

        Gets the iterator iterator<entry<string, object>> iterator = Entryset.iterator ();
        int index = 0; while (Iterator.hasnext ()) {entry<string, object&Gt
            Mapentry = Iterator.next ();
                        Get key and value from Mapentry create a key value object to store in the array try {Nvp[index] = new Namevaluepair (Mapentry.getkey (),
            New String (Mapentry.getvalue (). toString (). GetBytes ("UTF-8"), "UTF-8");
            catch (Unsupportedencodingexception e) {e.printstacktrace ();
        } index++; }///Determine if the NVP array is empty if (null!= NVP && nvp.length > 0) {//Deposit parameters to pos in Requestbody object
    Tmethod.setrequestbody (NVP);
        ///Execute Post method try {int statusCode = Httpclient.executemethod (Postmethod); Determine if successful if (StatusCode!= httpstatus.sc_ok) {System.err.println ("method faild:" + postmethod.getst
        Atusline ());
        //Get remotely returned data is = Postmethod.getresponsebodyasstream ();

        Encapsulating input Stream br = new BufferedReader (new InputStreamReader (IS, "UTF-8")); StringBuffer SBF = new StringBuffer ();
        String temp = null;
        while (temp = Br.readline ())!= null) {sbf.append (temp). Append ("\ r \ n");
    result = Sbf.tostring ();
    catch (IOException e) {e.printstacktrace ();
            Finally {//close resource if (null!= br) {try {br.close ();
            catch (IOException e) {e.printstacktrace ();
            } if (null!= is) {try {is.close ();
            catch (IOException e) {e.printstacktrace ();
    }//Release connection postmethod.releaseconnection ();
return result;
 }

}

The third way: Apache httpClient4.5

Package com.powerX.httpClient;

Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Map.Entry;
Import Java.util.Set;

Import org.apache.http.HttpEntity;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.ClientProtocolException;
Import Org.apache.http.client.config.RequestConfig;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.CloseableHttpResponse;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.message.BasicNameValuePair;
Import Org.apache.http.util.EntityUtils;

public class HttpClient4 {

public static string doget (string url) {closeablehttpclient httpclient = null;
    Closeablehttpresponse response = null;
    String result = "";
        try {//Create a httpclient instance httpclient = Httpclients.createdefault () By default configuration of the address;
        Create HttpGet remote Connection instance httpget HttpGet = new HttpGet (URL);
        Set request header information, authentication Httpget.setheader ("Authorization", "bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
                Set Configuration request parameters Requestconfig Requestconfig = Requestconfig.custom (). Setconnecttimeout (35000)//Connection Host service timeout . Setconnectionrequesttimeout (35000)//Request timeout. SetSocketTimeout (60000)//data read timeout. Bui
        LD ();
        Configure Httpget.setconfig (Requestconfig) for httpget instance settings;
        Executes GET request gets return object response = Httpclient.execute (HttpGet);
        Gets the returned data by returning the object httpentity entity = response.getentity ();
    Converts the result to a string by the ToString method in entityutils = entityutils.tostring (entity);catch (Clientprotocolexception e) {e.printstacktrace ();
    catch (IOException e) {e.printstacktrace ();
            Finally {//close resource if (null!= response) {try {response.close ();
            catch (IOException e) {e.printstacktrace ();
            } if (null!= httpclient) {try {httpclient.close ();
            catch (IOException e) {e.printstacktrace ();
}} return result; public static string doPost (String URL, map<string, object> parammap) {closeablehttpclient httpclient = null
    ;
    Closeablehttpresponse HttpResponse = null;
    String result = "";
    Create HttpClient Instance httpclient = Httpclients.createdefault ();
    Create HttpPost remote Connection instance HttpPost HttpPost = new HttpPost (URL);
    Configure request Parameter instance Requestconfig Requestconfig = Requestconfig.custom (). Setconnecttimeout (35000)/Set Connection Host service timeout        . Setconnectionrequesttimeout (35000)//Sets the connection request timeout. SetSocketTimeout (60000)//sets the Read data connection timeout.
    Build ();
    Configure Httppost.setconfig (Requestconfig) for httppost instance settings;
    Set Request Header Httppost.addheader ("Content-type", "application/x-www-form-urlencoded"); Encapsulates the POST request parameter if (null!= parammap && parammap.size () > 0) {list<namevaluepair> Nvps = new A
        Rraylist<namevaluepair> ();
        The entity set<entry<string is obtained by map integrated EntrySet method, object>> entryset = Parammap.entryset ();
        Loop traversal, get iterator iterator<entry<string, object>> iterator = Entryset.iterator ();
            while (Iterator.hasnext ()) {entry<string, object> mapentry = Iterator.next ();
        Nvps.add (New Basicnamevaluepair (Mapentry.getkey (), Mapentry.getvalue (). toString ()));
     ///Set the encapsulated request parameter try {httppost.setentity (new urlencodedformentity (Nvps, "UTF-8") for HttpPost;   catch (Unsupportedencodingexception e) {e.printstacktrace ();
        The try {//HttpClient object executes a POST request and returns the response parameter object HttpResponse = Httpclient.execute (HttpPost);
        Gets the response content from the response object httpentity entity = httpresponse.getentity ();
    result = entityutils.tostring (entity);
    catch (Clientprotocolexception e) {e.printstacktrace ();
    catch (IOException e) {e.printstacktrace ();
            Finally {//close resource if (null!= httpresponse) {try {httpresponse.close ();
            catch (IOException e) {e.printstacktrace ();
            } if (null!= httpclient) {try {httpclient.close ();
            catch (IOException e) {e.printstacktrace ();
}} return result;
 }

}

Sometimes when we use a POST request, the parameters that may be passed in are JSON or other formats, and then we need to change the request header and parameter setting information, taking httpClient4.5 as an example, change the following two-column configuration: httppost.setentity (new Stringentity ("Your JSON string")); Httppost.addheader ("Content-type", "Application/json").

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.