The use of httpclient in Java

Source: Internet
Author: User

HttpClient steps: 1. The steps to send get and POST requests using Apache HttpClient are as follows:

1. Create the Closeablehttpclient object using the Help class httpclients. 2. Create an HttpGet or HttpPost instance based on the type of HTTP request you want to send.
3. Use the AddHeader method to add the request header, such as User-agent, accept-encoding and other parameters.
4. For the POST request, create a Namevaluepair list and add all the form parameters. Then fill it into the httppost entity.
5. Obtain the Closeablehttpresponse instance by performing this httpget or HttpPost request
6. Get status codes, error messages, response pages, and so on from this closeablehttpresponse instance.
7. Finally close the httpclient resource.

2, the use of HttpClient send requests, receive response is very simple, generally need the following steps:

1. Create the HttpClient object, Httpclients.createdefault ().

2. Create an instance of the request method and specify the request URL. If you need to send a GET request, create a HttpGet object, or if you need to send a POST request, create a HttpPost object, HttpPost httppost = new HttpPost (URL).

3. If you need to send request parameters, you can call the HttpGet, HttpPost common setparams (Hetpparams params) method to add the request parameters, and for HttpPost objects, you can also call Setentity ( Httpentity entity) method to set the request parameters. list<namevaluepair> valuepairs = new linkedlist<namevaluepair> (); Valuepairs.add (New BasicNameValuePair ( Entry.getkey (), Entry.getvalue ())); Httppost.setentity (formentity).

4. Call the Execute (httpurirequest request) of the HttpClient object to send the request, which returns a HttpResponse.

5. Call HttpResponse's Getallheaders (), Getheaders (String name) and other methods to get the server's response header; call HttpResponse getentity () The Httpentity method gets the object that wraps the server's response content. This object is used by the program to obtain the server's response content.

6. Release the connection. The connection must be released regardless of the success of the execution method

HttpClient instance: Instance one:
Package Http;import Java.io.ioexception;import Java.io.unsupportedencodingexception;import java.util.HashMap; Import Java.util.linkedlist;import java.util.list;import Java.util.map;import Java.util.map.entry;import Org.apache.commons.httpclient.httpclient;import Org.apache.http.httpentity;import Org.apache.http.HttpResponse; Import Org.apache.http.namevaluepair;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httppost;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.util.entityutils;import Org.apache.http.impl.client.httpclients;public class Httptest {public Boolean isrequestsuccessful (httpresponse HttpResponse) {return Httpresponse.getstatusline (). Getstatuscode () ==200;} public string HttpPost (string param1,string param2,string url) throws exception{map<string,string> Personmap = new Hashmap<string,string> ();p ersonmap.put ("param1", param1);p ersonmap.put ("pAram1 ", param2); list<namevaluepair> list = new linkedlist<namevaluepair> (); for (entry<string,string> Entry: Personmap.entryset ()) {List.add (New Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()));} HttpPost HttpPost = new HttpPost (URL); Urlencodedformentity formentity = new urlencodedformentity (list, "Utf-8"); httppost.setentity (formentity); HttpClient httpcient = Httpclients.creatdefault (); HttpResponse HttpResponse = Null;try{httpresponse = Httpclient.execute (HttpPost); Httpentity httpentity = httpresponse.getentity (); String response = entityutils.tostring (httpentity, "Utf-8"); return response;} catch (Clientprotocolexception e) {System.out.println ("HTTP request failed, uri{},exception{}");} catch (IOException e) {System.out.println ("HTTP request failed, uri{},exception{}");} return null;}}

  

Example two:
Package Com.kingdee.opensys.common.util.http;import Java.io.ioexception;import Java.util.concurrent.locks.Lock; Import Java.util.concurrent.locks.reentrantlock;import Org.apache.http.httpentity;import Org.apache.http.client.clientprotocolexception;import org.apache.http.client.entity.GzipDecompressingEntity; Import Org.apache.http.client.methods.closeablehttpresponse;import Org.apache.http.client.methods.httprequestbase;import Org.apache.http.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclientbuilder;import Org.apache.http.impl.conn.poolinghttpclientconnectionmanager;import Org.apache.http.util.entityutils;import Org.slf4j.logger;import Org.slf4j.loggerfactory;public class Httpclienthelper {private static Logger Logger = Loggerfactory.getlogger (httpclienthelper.class);p rivate static Httpclienthelper instance = Null;private static Lock lock = new Reentrantlock ();p rivate static closeablehttpclient httpclient;public Httpclienthelper () {instance = this;} public static Httpclienthelper gethttpclient () {if (instance = = null) {Lock.lock (); try{instance = new Httpclienthelper ();} catch (Exception e) {e.printstacktrace ();} Finally{lock.unlock ();}} return instance;} public void init () {Poolinghttpclientconnectionmanager pool = new Poolinghttpclientconnectionmanager (); Pool.setmaxtotal;p Ool.setdefaultmaxperroute (), httpClient = Httpclientbuilder.create (). Setconnectionmanager (Pool). build ();} Public byte[] Executeandreturnbyte (Httprequestbase request) throws exception{httpentity entity = NULL; Closeablehttpresponse response = null;byte[] base = new Byte[0];if (request==null) {return base;} if (httpclient==null) {init ();} if (httpclient==null) {logger.error ("HTTP Get Exception"); return base;} Response = Httpclient.execute (request); entity = Response.getentity (); if (Response.getstatusline (). Getstatuscode () = = {String encode = ("" +response.getfirstheader ("content-encoding")). toLowerCase (); if (Encode.indexof ("gzip") > 0) {entity = new gzipdecompressingentity (entity);} Base = Entityutils.toByteArray (entity);} Else{logger.error ("" +response.getstatusline (). Getstatuscode ());} entityutils.consumequietly (entity); Response.close (); Httpclient.close (); return base;} Public String Execute (httprequestbase request) throws exception{byte[] base = executeandreturnbyte (Request); if (base== NULL) {return null;} string result = new String (Base, "UTF-8"); return result;}} Package Com.kingdee.opensys.common.util.http;import Java.io.unsupportedencodingexception;import Java.util.iterator;import Java.util.linkedlist;import Java.util.list;import Java.util.map;import Org.apache.http.httpentity;import Org.apache.http.client.config.requestconfig;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httppost;import Org.apache.http.entity.stringentity;import Org.apache.http.message.basicnamevaluepair;import Javax.servlet.http.httpservletrequest;public class Httphelper {private static String UTF8 = "UTF-8";p rivate static Requestconfig requestconfig;public Static StringPost (map<string,string> header,map<string,string> params,string URL) throws Exception{httppost post = null ;p ost = new HttpPost (URL), if (Header!=null) {for (String Key:header.keySet ()) {Post.addheader (key, Header.get (key));}} if (params!=null) {list<basicnamevaluepair> List = new linkedlist<basicnamevaluepair> ();p ost.setconfig ( Getrequestconfig ()); for (String Key:params.keySet ()) {List.add (New Basicnamevaluepair (Key,params.get (key));} urlencodedformentity entity = new Urlencodedformentity (List,utf8);p ost.setentity (entity); Return Httpclienthelper.gethttpclient (). Execute (POST);} public static String post (map<string,string> header,string jsonobject,string URL) throws Exception{httppost post = Null;post = new HttpPost (URL), if (Header!=null) {for (String Key:header.keySet ()) {Post.addheader (key, Header.get (key)) ;}} if (Jsonobject.isempty ()) {throw new Exception ("Jsonobject cannot be empty! ");} httpentity entity = new Stringentity (Jsonobject, "UTF-8"); return Httpclienthelper.gethttpclient (). exEcute (post);} public static String post (map<string,string> params,string URL) throws Exception{httppost post = Null;post = new Htt Ppost (URL); list<basicnamevaluepair> list = new linkedlist<basicnamevaluepair> ();p ost.setconfig (GetRequestConfig () ); for (String Key:params.keySet ()) {List.add (New Basicnamevaluepair (Key,params.get (key)));} urlencodedformentity entity = new Urlencodedformentity (List,utf8);p ost.setentity (entity); return Httpclienthelper.gethttpclient (). Execute (POST);} public static Requestconfig Getrequestconfig () {if (requestconfig==null) {requestconfig = Requestconfig.custom (). Setconnectionrequesttimeout (20000). Setconnecttimeout (20000). SetSocketTimeout (20000). build ();} return requestconfig;} public static String Getclientip (HttpServletRequest request) {String IP = Request.getheader ("x-forwarded-for"); if (ip== null| | Ip.length () ==0| | " Unknown ". Equalsignorecase (IP)) {IP = request.getheader (" Proxy-client-ip ");} if (ip==null| | Ip.length () ==0| | " Unknown ". Equalsignorecase (IP)) {IP = reQuest.getheader ("Wl-proxy-client_ip");} if (ip==null| | Ip.length () ==0| | " Unkonwn ". Equalsignorecase (IP)) {IP = request.getremoteaddr ();} if (Ip.length () <5) {ip= "0.0.0.0";} return IP;}}

  

The use of httpclient in Java

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.