Java4android HttpClient Getting started using the code set

Source: Internet
Author: User
Tags form post getmessage

This article will guide how to use the various functions and features of httpclient from a code perspective.

First Program

Import Org.apache.commons.httpclient.*;import Org.apache.commons.httpclient.methods.*;import Org.apache.commons.httpclient.params.httpmethodparams;import java.io.*;p Ublic class Httpclienttutorial {private  static String URL = "http://www.apache.org/";    public static void Main (string[] args) {//Create an instance of HttpClient.    HttpClient client = new HttpClient ();    Create a method instance.        GetMethod method = new GetMethod (URL); Provide custom retry handler is necessary Method.getparams (). Setparameter (Httpmethodparams.retry_handler, New De    Faulthttpmethodretryhandler (3, false));      try {//Execute the method.      int StatusCode = Client.executemethod (method);      if (statusCode! = HTTPSTATUS.SC_OK) {System.err.println ("Method failed:" + method.getstatusline ());      }//Read the response body.      byte[] Responsebody = Method.getresponsebody ();      Deal with the response. Use caution:ensure correct character EncodiNg and is not binary data System.out.println (new String (responsebody));      } catch (HttpException e) {System.err.println ("Fatal protocol violation:" + e.getmessage ());    E.printstacktrace ();      } catch (IOException e) {System.err.println ("Fatal Transport Error:" + e.getmessage ());    E.printstacktrace ();      } finally {//Release the connection.    Method.releaseconnection (); }    }}


Impersonate HTTP Web page log in

Package Org.apache.http.examples.client;import Java.net.uri;import Java.util.list;import Org.apache.http.httpentity;import Org.apache.http.client.methods.closeablehttpresponse;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httpurirequest;import Org.apache.http.client.methods.requestbuilder;import Org.apache.http.cookie.cookie;import Org.apache.http.impl.client.basiccookiestore;import Org.apache.http.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclients;import org.apache.http.util.entityutils;/** * A example that demonstrates how HttpClient APIs can be used to perform * form-based logon. */public class Clientformlogin {public static void main (string[] args) throws Exception {Basiccookiestore Cook        Iestore = new Basiccookiestore (); Closeablehttpclient httpclient = Httpclients.custom (). Setdefaultcookiestore (Cookiestore). b        Uild (); try {httpget HttpGet = new HTTPGET ("https://someportal/");            Closeablehttpresponse response1 = Httpclient.execute (HttpGet);                try {httpentity entity = response1.getentity ();                System.out.println ("Login form get:" + response1.getstatusline ());                Entityutils.consume (entity);                System.out.println ("Initial Set of Cookies:");                list<cookie> cookies = cookiestore.getcookies ();                if (Cookies.isempty ()) {System.out.println ("None");  } else {for (int i = 0; i < cookies.size (); i++) {System.out.println ("-" +                    Cookies.get (i). toString ());            }}} finally {Response1.close ();                    } httpurirequest Login = Requestbuilder.post (). Seturi (New URI ("https://someportal/")) . Addparameter ("IDToken1", "username"). Addparameter("IDToken2", "password"). Build ();            Closeablehttpresponse response2 = httpclient.execute (login);                try {httpentity entity = response2.getentity ();                System.out.println ("Login form get:" + response2.getstatusline ());                Entityutils.consume (entity);                System.out.println ("Post Logon Cookies:");                list<cookie> cookies = cookiestore.getcookies ();                if (Cookies.isempty ()) {System.out.println ("None");  } else {for (int i = 0; i < cookies.size (); i++) {System.out.println ("-" +                    Cookies.get (i). toString ());            }}} finally {Response2.close ();        }} finally {Httpclient.close (); }    }}

Multi-Form Post example
/** * Example How to use Multipart/form encoded POST request. */public class Clientmultipartformpost {public static void main (string[] args) throws Exception {if (Args.leng            Th! = 1) {System.out.println ("File Path not given");        System.exit (1);        } closeablehttpclient httpclient = Httpclients.createdefault (); try {httppost httppost = new HttpPost ("http://localhost:8080" + "/servlets-examples/servlet            /requestinfoexample ");            Filebody bin = new Filebody (new File (Args[0]));            Stringbody comment = new Stringbody ("A binary file of some kind", contenttype.text_plain); Httpentity reqentity = Multipartentitybuilder.create (). Addpart ("Bin", bin). Addpart            ("comment", comment). build ();            Httppost.setentity (reqentity);            SYSTEM.OUT.PRINTLN ("Executing request" + httppost.getrequestline ()); CloseablehttpreSponse response = Httpclient.execute (HttpPost);                try {System.out.println ("----------------------------------------");                System.out.println (Response.getstatusline ());                Httpentity resentity = response.getentity (); if (resentity! = null) {System.out.println ("Response Content Length:" + resentity.getcontentlength ())                ;            } entityutils.consume (resentity);            } finally {response.close ();        }} finally {Httpclient.close (); }    }}

Use ResponseHandler to simplify handling of HTTP response and resource release

/** * This example demonstrates the use of the {@link ResponseHandler} to simplify * the process of processing the HTTP re Sponse and releasing associated resources. */public class Clientwithresponsehandler {public final static void main (string[] args) throws Exception {Close        Ablehttpclient httpclient = Httpclients.createdefault ();            try {httpget httpget = new HttpGet ("http://localhost/");            SYSTEM.OUT.PRINTLN ("Executing request" + httpget.getrequestline ()); Create A custom response handler responsehandler<string> ResponseHandler = new Responsehandler<stri Ng> () {public String handleresponse (final HttpResponse response) throws CLIENTP                    Rotocolexception, ioexception {int status = Response.getstatusline (). Getstatuscode ();     if (Status >= && status <) {Httpentity entity = response.getentity ();                   return entity! = null?                    Entityutils.tostring (entity): null;                    } else {throw new clientprotocolexception ("Unexpected response status:" + status);            }                }            };            String responsebody = Httpclient.execute (HttpGet, ResponseHandler);            System.out.println ("----------------------------------------");        System.out.println (responsebody);        } finally {httpclient.close (); }    }}

Example of use of Get methods in multithreaded environments

/** * An example this performs GETs from multiple threads. * */public class Clientmultithreadedexecution {public static void main (string[] args) throws Exception {//Cre        Ate an HttpClient with the Threadsafeclientconnmanager.        This connection manager must is used if more than one thread would//be using the HttpClient.        Poolinghttpclientconnectionmanager cm = new Poolinghttpclientconnectionmanager ();        Cm.setmaxtotal (100);        Closeablehttpclient httpclient = Httpclients.custom (). Setconnectionmanager (CM). Build (); try {//Create an array of URIs to perform GETs on string[] Uristoget = {"Htt p://hc.apache.org/"," http://hc.apache.org/httpcomponents-core-ga/"," http://hc.apache.org/h            Ttpcomponents-client-ga/",};            Create a thread for each URI getthread[] threads = new Getthread[uristoget.length]; FoR (int i = 0; i < threads.length; i++) {HttpGet httpget = new HttpGet (Uristoget[i]);            Threads[i] = new GetThread (httpclient, HttpGet, i + 1); }//Start the threads for (int j = 0; J < Threads.length; J + +) {Threads[j].start            (); }//Join the threads for (int j = 0; J < Threads.length, J + +) {Threads[j].join ()            ;        }} finally {Httpclient.close ();     }}/** * A thread that performs A GET.        */Static Class GetThread extends Thread {private final closeablehttpclient httpClient;        Private final HttpContext context;        Private final HttpGet HttpGet;        private final int id;            Public GetThread (Closeablehttpclient httpClient, httpget httpget, int id) {this.httpclient = httpClient;            This.context = new Basichttpcontext ();            This.httpget = HttpGet; THis.id = ID;         }/** * Executes the GetMethod and prints some status information. */@Override public void Run () {try {System.out.println (id + "-on-get so                Mething from "+ Httpget.geturi ());                Closeablehttpresponse response = Httpclient.execute (httpget, context);                    try {System.out.println (id + "-get executed");                    Get the response body as an array of bytes httpentity entity = response.getentity ();                        if (Entity! = null) {byte[] bytes = Entityutils.tobytearray (entity);                    System.out.println (id + "-" + bytes.length + "bytes read");                }} finally {Response.close ();            }} catch (Exception e) {System.out.println (id + "-error:" + E); }        }    }}






Java4android HttpClient Getting started using the code set

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.