Android HTTP Request Method Summary

Source: Internet
Author: User

Recently compared the JDK used in Android HttpURLConnection and Apache Httpclien access network resources, summed up the HTTP protocol information. As follows:

JDK's httpurlconnection:

(1) Get request

Public String Executehttpget () {

String result = null;

URL url = null;

HttpURLConnection connection;

InputStreamReader in =null;

try{

url = new URL ("Http://10.0.2.2.:8888/data/get/?token=alexzhou");

Connection = (httpurlconnection) url.openconnection ();

in = new InputStream (Connection.getinputstream ());

BufferedReader BufferedReader = new BufferedReader (in);

StringBuffer str = new StringBuffer ();

String line =null;

while (line = Bufferedreader.readline ()) = null) {

Str.append (line);

}

}catch (Exception e) {

E.printstacktrace ();

}finally{

if (connection! = null) {

Connection.disconnect ();

} if (in = null) {

try{

In.close ();

}catch (IOException e) {

E.printstacktrace ();

}

}

}

return result;

}

(2) Post request

Public String Executehttppost () {

String result = null;

URL URL =null;

HttpURLConnection connection = null;

InputStream in = null;

try{

url = new URL ("Http://10.0.2.2:8888/data/post");

Connection = (httpurlconnection) url.openconnection ();

Connection.setdoinput (TRUE);

Connection.setdooutput (TRUE);

Connection.setrequestmethod ("POST");

Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");

Connection.setrequestproperty ("Charset", "utf-8");

DataOutputStream DOP = new DataOutputStream (Connection.getoutputstream ());

Dop.writebytes ("Token=alexzhou");

Dop.flush ();

Dop.close ();

in = new InputStreamReader (Connection.getinputstream ());

BufferedReader BufferedReader = new BufferedReader (in);

StringBuffer str = new StringBuffer ();

String line = null;

while (line = Bufferedreader.readline ()) = null) {

Str.append (line);

}

result = Str.tostring ();

}catch (Exception e) {

E.printstacktrace ()

}finally{

if (connection! = null) {

Connection.disconnect ();

}if (In! = null) {

try{

In.close ();

}catch (IOException e) {

E.printstacktrace ();

}

}

}

return result;

}

If you have Chinese in the parameter, you can encode and decode it in the following way:

urlencoder.encode ("Test", "Utf-8");urldecoder.decode ("Test", "Utf-8"); Apache's httpclient:
(1) Get request

Public String Executeget () { 

     String result = null;

BufferedReader reader = null;

   try{

HttpClient client = new Defaulthttpclient ();

HttpGet request = new HttpGet ();

     request.setURL(new URL("http://10.0.2.2:8888/data/get/?token=alexzhou"));

HttpResponse respone =client.execute (Request); 

    reader = newBufferedReader(newInputStreamReader(response.getEntity().getContent()));

    StringBuffer strBuffer = newStringBuffer("");

     String line = null;

     while((line = reader.readLine()) != null) {

          strBuffer.append(line);

   }

       result = strBuffer.toString();

   catch(Exception e) {

           e.printStackTrace();

        finally{

           if(reader != null) {

             try{

                 reader.close();

                 reader = null;

              catch(IOException e) {

                 e.printStackTrace();

              }

            }

        }

        returnresult;

}

(2) Post mode

public String executePost() {               String result =  null ;
      BufferedReader reader =  null ;     try {

        HttpClient client = new DefaultHttpClient();

        HttpPost request = newHttpPost();

        request.setURI(newURI("http://10.0.2.2:8888/data/post/"));

        List<NameValuePair> postParameters = newArrayList<NameValuePair>();

        postParameters.add(newBasicNameValuePair("token""alexzhou"));

        UrlEncodedFormEntity formEntity = newUrlEncodedFormEntity(postParameters);

        request.setEntity(formEntity);

        HttpResponse response = client.execute(request);

        reader = newBufferedReader(newInputStreamReader(response.getEntity().getContent()));

         StringBuffer strBuffer =  new StringBuffer( "" );                     String line =  null ;          while ((line = reader.readLine()) !=  null ) {               strBuffer.append(line);            }               result = strBuffer.toString();          catch (Exception e) {              e.printStackTrace();          finally {              if (reader !=  null ) {                  try {                      reader.close();                      reader =  null ;                  catch (IOException e) {                      e.printStackTrace();                  }              }          }          return result;      }

Android HTTP Request Method Summary

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.