HttpClient HTTP request steps

Source: Internet
Author: User

Apache provides a set of useful APIs for client HTTP requests that can be used when Android writes HTTP request operations, summarizing the request steps below.

One. Create a List<namevaluepair> object to provide the form with the parameters that are stored in the list:

List<namevaluepair> List=getrequestparams (Requestparams);

Convert the requested map to a list

private static list<namevaluepair> Getrequestparams (map<string,string> requestparams) {

List<namevaluepair> List=null;

List=new arraylist<namevaluepair> ();

Build iterators

Iterator Iterator=requestparams.entryset (). Iterator ();

while (Iterator.hasnext ()) {

Map.entry interface, separating key-value pairs

Map.entry<string,string>entry = (map.entry<string,string>) iterator.next ();

List.add (New Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()));

}

return list;

}

II. Create a HttpClient object with singleton mode:

HttpClient mhttpclient =singletonhttpclients.getinstancehttpclients ();


public class Singletonhttpclients {

Private singletonhttpclients () {}

private static final HttpClient mhttpclient=new defaulthttpclient ();

public static HttpClient getinstancehttpclients () {

return mhttpclient;

}

}

Create a HttpPost object and submit the form as a post:

HttpPost Post=buildhttppost (List,requestpath);


private static HttpPost Buildhttppost (list<namevaluepair> list,string requestpath) {

HttpPost Post=null;

try{

Urlencodedformentity postentity=new urlencodedformentity (list, "Utf-8");

Post=new HttpPost (Requestpath);

Post.setentity (postentity);

}

catch (Unsupportedencodingexception e) {

E.printstacktrace ();

}

return post;

}


. Executes the Post method, requests the server, returns the data stream (creates the HttpResponse object to receive the server return; Httpentity object to get the server to return content and return as a stream)

InputStream serverinputstream =getseverresponse (mhttpclient,post)


private static InputStream Getseverresponse (HttpClient mhttpclient,httppost Post) {

try {

HttpResponse Mresponse=mhttpclient.execute (POST);

Httpentity mentity=mresponse.getentity ();

return Mentity.getcontent ();

}

catch (Sockettimeoutexception e) {

E.printstacktrace ();

}

catch (IOException e) {

E.printstacktrace ();

}

return null;

}

The input stream is read into and processed into a string

private static InputStream Getseverresponse (HttpClient mhttpclient,httppost Post)


private static InputStream Getseverresponse (HttpClient mhttpclient,httppost Post) {

try {

HttpResponse Mresponse=mhttpclient.execute (POST);

Httpentity mentity=mresponse.getentity ();

return Mentity.getcontent ();

}

catch (Sockettimeoutexception e) {

E.printstacktrace ();

}

catch (IOException e) {

E.printstacktrace ();

}

return null;

}


The complete code is as follows:

public class Httputils {

/**

*

* @param requestpath Server request path

* @param requestparams Request Parameters

* @param the encoding format of the Requestencode request form

* @param the encoding format of the Responseencode request return body

* @return

*/

public static string Getresponsestring (String Requestpath,

Map<string,string>requestparams,string requestencode,string Responseencode) {

Convert Request parameters to list

List<namevaluepair> List=getrequestparams (Requestparams);

if (list!=null) {

Create HttpPost object, submit form as Post

HttpPost Post=buildhttppost (List,requestpath);

Create a HttpClient object

HttpClient mhttpclient =singletonhttpclients.getinstancehttpclients ();

if (mhttpclient!=null) {

Reads the server return result as a stream

InputStream serverinputstream =getseverresponse (mhttpclient,post);

if (serverinputstream!=null) {

Convert server return results to a string

Return (getstreamtostring (Serverinputstream,responseencode));

}

else {

return "Internetexception";

}

}

else {

return "Singletonexception";

}


}

else return "paramsexception";

}


/**

* Convert the requested map to list

* @param requestparams

* @return

*/

private static list<namevaluepair> Getrequestparams (map<string,string> requestparams) {

List<namevaluepair> List=null;

List=new arraylist<namevaluepair> ();

Build iterators

Iterator Iterator=requestparams.entryset (). Iterator ();

while (Iterator.hasnext ()) {

Map.entry interface, separating key-value pairs

Map.entry<string,string>entry = (map.entry<string,string>) iterator.next ();

List.add (New Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()));

}

return list;

}


/**

* Put list in request form

* Instantiating HttpPost objects

* @param list

* @param Requestpath

* @return

*/

private static HttpPost Buildhttppost (list<namevaluepair> list,string requestpath) {

HttpPost Post=null;

try{

Urlencodedformentity postentity=new urlencodedformentity (list, "Utf-8");

Post=new HttpPost (Requestpath);

Post.setentity (postentity);

}

catch (Unsupportedencodingexception e) {

E.printstacktrace ();

}

return post;

}


/**

* Execute POST method, request server, return data stream

* @param mhttpclient

* @param post

* @return

*/

private static InputStream Getseverresponse (HttpClient mhttpclient,httppost Post) {

try {

HttpResponse Mresponse=mhttpclient.execute (POST);

Httpentity mentity=mresponse.getentity ();

return Mentity.getcontent ();

}

catch (Sockettimeoutexception e) {

E.printstacktrace ();

}

catch (IOException e) {

E.printstacktrace ();

}

return null;

}


/**

* Convert data flow in the network into strings

* @param inputstream

* @param encode

* @return

*/

private static String getstreamtostring (InputStream inputstream,string encode) {

StringBuffer stringbuffer=new StringBuffer ();

try {

BufferedReader mbufferedreader=new BufferedReader (New InputStreamReader (Inputstream,encode));

String Tmp=new string ();

while ((Tmp=mbufferedreader.readline ())!=null) {

Stringbuffer.append (TMP);

}

Mbufferedreader.close ();

return stringbuffer.tostring ();

}

catch (Unsupportedencodingexception e) {

E.printstacktrace ();

return "Switchexception";

}

catch (IOException e) {

E.printstacktrace ();

return "Switchexception";

}

}

}


HttpClient HTTP request steps

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.