HttpURLConnection send a GET, POST request

Source: Internet
Author: User

Before the use of asynchttpclient, Encountered in the Android6.0 after the httpclient problem, and then the official update of 1.4. Version 9 replaced the httpclient as a third-party cz.msebera.android.httpclient. Knowing that Google removed httpclient after Android6.0, it is recommended to use HttpURLConnection to implement HTTP requests, and many other third-party network request frameworks are instead based on httpurlconnection, so it is considered necessary to familiarize themselves with the basic Method.

The process used:

1

Create a URL object

URL url = new URL ("http://qq.com");

2

Instantiation of HttpURLConnection

conn = (httpurlconnection) url.openconnection ();

3

Set the related properties of the request, post value, etc.

Conn.setrequestmethod ("POST"), Conn.setdooutput (), etc.

4

Get the return code to determine whether the connection is successful or not

if (conn.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK)

5

Read input stream

InputStream is = Conn.getinputstream ();

6

Close connection, input stream

Conn.disconnect (); Is.close ();

Get Request:

//httpurlconnection The default is a GET request, and in the simplest case nothing needs to be set.

conn = (httpurlconnection) url.openconnection ();

InputStream is = Conn.getinputstream ();


Get Request Sample code:

Try {    url url = new url ("http://112.124.63.181/mm/Api/Public/ Timestamp ");    conn =  (httpurlconnection)  url.openconnection ();     inputstream is = conn.getinputstream ();     reader =  new bufferedreader (New inputstreamreader (IS));     STRINGBUILDER SB  = new stringbuilder ();     string line;    while   ((Line = reader.readline ())  != null)  {         sb.append (line);     }    showtext (sb.toString ());}  catch  (ioexception e)  {    e.printstacktrace ();} finally {    if  (conn != null) {conn.disconnect ();}     if  (reader != null) {        try {             reader.close ();        } catch  (IOException e)  {e.printstacktrace ();}     }}

Post Request:

The main differences between post and get:

Conn.setrequestmethod ("POST");

Conn.setdooutput (TRUE);// allow data to be submitted to the server

Conn.setusecaches (false);//post is not cached

String BODY = "PASSWORD=E10ADC3949BA59ABBE56E057F20F883E&USERNAME=TEST3";

OutputStream OS = Conn.getoutputstream ();

Os.write (Body.getbytes ());

Os.flush ();

Os.close ();

InputStream is = Conn.getinputstream ();

...

Submit data:

OutputStream OS = Conn.getoutputstream ();

Os.write (Body.getbytes ());

Os.flush ();

Os.close ();

Output a string-converted byte array directly using a low-level byte stream.

DataOutputStream dos = new DataOutputStream (OS);

OutputStreamWriter writer = new OutputStreamWriter (OS);

BufferedWriter writer = new BufferedWriter (newoutputstreamwriter (OS));

Using advanced character streams makes it easier to output strings, files, and more.

Post Request Sample code:

string urlstring =  "Http://120.77.156.236/mm/Api/Base/checkLogin"; string bodystring =  "Password=e10adc3949ba59abbe56e057f20f883e&username=test3"; Url url = new url (urlstring);conn =  (httpurlconnection)  url.openConnection ( ); Conn.setrequestmethod ("POST"); Outputstream os = conn.getoutputstream (); Os.write ( Bodystring.getbytes ("Utf-8")); Os.flush (); Os.close ();if  (Conn.getresponsecode ()  ==  HTTPURLCONNECTION.HTTP_OK)  {    inputstream is = conn.getinputstream () ;     bufferedreader reader = new bufferedreader (new  InputStreamReader (IS));     stringbuilder sb = new stringbuilder ();     String line;    while  (line = reader.readline ())  != null)  {        sb.append (line); &Nbsp;   }    return sb.tostring ();} 

Common Setup methods:

// set the request method, default is Get

Conn.setrequestmethod ("GET");

// Setting the connection server timeout

Conn.setconnecttimeout (8000);

// setting the Read server data timeout

Conn.setreadtimeout (5000);

// set whether to use the cache

Conn.setusecaches (TRUE);

// set the character set used

Conn.setrequestproperty ("Charset", "UTF-8");

// setting content Type information

Conn.setrequestproperty ("Content-type", "Application/json");

// Setting Custom Parameters

Conn.setrequestproperty ("MyKey", "myvalue");

// set whether to allow output , default to False, must be true when post data is submitted

Conn.setdooutput

// sets whether to allow input, which defaults to true, so that getInputStream has a value

Conn.setdoinput

// set the stream size for each transfer to prevent the phone from running out of memory

Conn.setchunkedstreamingmode (51200);

// Starting a connection does not require an explicit call, called getInputStream or Getresponsecode, and so on.

Conn.connect ();


This article is from a "sword Siege" blog, please make sure to keep this source http://weijiancheng.blog.51cto.com/10190955/1928480

HttpURLConnection send a GET, POST request

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.