Java uses httpclient to encapsulate post requests and get requests

Source: Internet
Author: User
Tags stringbuffer

In our programmers ' careers, we often have to reuse code, so we should get into the habit of sorting the code from time to time, and here's the code for the HttpClient post and get requests that I encapsulated earlier:


Package Com.marco.common;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.net.URI;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;

Import Java.util.Map;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.HttpStatus;
Import Org.apache.http.NameValuePair;
Import Org.apache.http.StatusLine;
Import org.apache.http.client.HttpClient;
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.entity.StringEntity;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.DefaultHttpClient;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.message.BasicNameValuePair;
Import Org.apache.http.protocol.HTTP; Import Org.apache.http.util.EnTityutils;

Import Org.apache.log4j.Logger;  /** * @author Horse strings * @date October 23, 2017 PM 2:49 * HttpClient Tool Class * * public class Httputil {private static Logger Logger

	= Logger.getlogger (Httputil.class); /** * GET request * @return/public static string doget (string url) {try {httpclient client = new De
            Faulthttpclient ();
            Send GET request HttpGet = new HttpGet (URL);
 
            HttpResponse response = Client.execute (request); /** request was sent successfully and received a response **/if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {/** Read service
                
                Returns the JSON string data **/string strresult = Entityutils.tostring (Response.getentity ());
            return strresult;
        } catch (IOException e) {e.printstacktrace ();
	return null; /** * POST request (parameters for Key-value format) * @param URL * @param params * @return/public static StringDoPost (String URL, Map params) {bufferedreader in = null;  
            try {//define httpclient httpclient client = new Defaulthttpclient ();  
            Instantiate HTTP method HttpPost request = new HttpPost ();
            
            Request.seturi (new URI (URL)); 
            Set parameter list<namevaluepair> Nvps = new arraylist<namevaluepair> (); for (Iterator iter = Params.keyset (). iterator (); Iter.hasnext ();)
    			{String name = (string) iter.next ();
    			String value = string.valueof (params.get (name));
    			
    			Nvps.add (New Basicnamevaluepair (name, value));
    		SYSTEM.OUT.PRINTLN (name + "-" +value); } request.setentity (New Urlencodedformentity (nvps,http).
            
            Utf_8));  
            HttpResponse response = Client.execute (request);
            int code = Response.getstatusline (). Getstatuscode (); if (code = = 200) {//request succeeded in = new BufferedReader (New InputstreAmreader (Response.getentity (). GetContent (), "Utf-8"));  
                StringBuffer sb = new StringBuffer ("");  
                String line = "";  
                String NL = System.getproperty ("Line.separator");  
                while (line = In.readline ())!= null) {Sb.append (line + NL);  
                
                } in.close ();
            return sb.tostring ();
            	} else{//System.out.println ("Status code:" + code);
            return null;
        	
        	} catch (Exception e) {e.printstacktrace ();
        return null; }/** * POST request (parameter to request JSON format) * @param URL * @param params * @return/public static String DoPost (Strin
		G URL, String params) throws Exception {closeablehttpclient httpclient = Httpclients.createdefault (); HttpPost HttpPost = new HttpPost (URL);//Create HttpPost httppost.seTheader ("Accept", "Application/json");
    	Httppost.setheader ("Content-type", "Application/json");
    	String CharSet = "UTF-8";
    	stringentity entity = new Stringentity (params, charSet);        
        Httppost.setentity (entity);
        
        Closeablehttpresponse response = null;
            try {response = Httpclient.execute (HttpPost);
            Statusline status = Response.getstatusline ();
            int state = Status.getstatuscode ();
            	if (state = = HTTPSTATUS.SC_OK) {httpentity responseentity = response.getentity ();
            	String jsonstring = entityutils.tostring (responseentity);
            return jsonstring;
			else{Logger.error ("Request returned: +state+" ("+url+")); } finally {if (response!= null) {try {Response.close
                ();
                catch (IOException e) {e.printstacktrace ();
          }  try {httpclient.close ();
			catch (IOException e) {e.printstacktrace ();
	} return null;
 }
	
}

HttpClient is a very common tool, in the development of the project, often need to request a Third-party interface, I have sorted out this code, later looking back when it is convenient.
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.