HttpURLConnection Basic Use

Source: Internet
Author: User

From https://developer.android.com/reference/java/net/HttpURLConnection.html

HttpURLConnection:

A URLConnection with support for Http-specific features. See the spec for details.

Uses of this class follow a pattern:

  1. Obtain a new by HttpURLConnection calling and casting the result to URL.openConnection() HttpURLConnection .
  2. Prepare the request. The primary property of a request was its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  3. Optionally upload a request body. Instances must is configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream() .
  4. Read the response. Response headers typically include metadata such as the Response body ' s content type and length, modified dates and Sessio n Cookies. The response body may is read from the stream returned by getInputStream() . If The response has no body, then the method returns an empty stream.
  5. Disconnect. Once The response body has been read, the HttpURLConnection should is closed by calling disconnect() . Disconnecting releases the resources held by a connection so they could be closed or reused.

Chinese explanation:

A urlconnection that supports HTTP-specific features.

Use this class to follow the following pattern:

1. Obtain a new HttpURLConnection object by calling Url.openconnection (), and cast its result to httpurlconnection.

2. Prepare the request. The primary parameter of a request is its URI. The request header may also contain metadata such as certificates, preferred data types and session cookies.

3. Can selectively upload a request body. The HttpURLConnection instance must be set to Setdooutput (true) if it contains a request body. Data is transferred by writing data to an output stream returned by Getoutstream ().

4. Read the response. The response header typically contains metadata such as the content type and length of the response body, modification date and session cookies. The response body can be read by the input stream returned by getInputStream. If the response has no response body, the method returns an empty stream.

5. Close the connection. Once a response body has been read, the HttpURLConnection object should be closed by calling disconnect (). Disconnecting frees up resources that are owned by a connection so that they can be shut down or reused.

From the above words and recent studies can be summed up:

About the operation and use of httpurlconnection, more is the get and post two kinds of

The main process:

Create a URL instance and open URLConnection
URL url=new URL ("http://www.baidu.com"); HttpURLConnection Connection= (httpurlconnection) url.openconnection ();
Setting Connection Parameters

Common methods:

Setdoinput

Setdooutput

Setifmodifiedsince: Set the last modified time of the cache page (reference from: http://blog.csdn.net/stanleyqiu/article/details/7717235)

Setusecaches

Setdefaultusecaches

Setallowuserinteraction

Setdefaultallowuserinteraction

Setrequestmethod:httpurlconnection default to use the Get method

Set Request Header Parameters

Common methods:

Setrequestproperty (Key,value)

Addrequestproperty (Key,value)

The difference between Setrequestproperty and Addrequestproperty is that setrequestproperty will overwrite all values of the existing key, with the effect of 0 re-assignment. Addrequestproperty, on the other hand, continues to add other value based on the original key.

Common settings:

To set the request data type:

Connection.setrequestproperty ("Content-type", "Application/x-javascript->json");// JSON format Data connection.addrequestproperty ("Content-type", "application/x-www-form-urlencoded");//default browser encoding type , Http://www.cnblogs.com/taoys/archive/2010/12/30/1922186.htmlconnection.addRequestProperty ("Content-type" , "multipart/form-data;boundary=" +boundary);//post request, encoding type when uploading data, and delimiter specified

Connection.setrequestproperty ("Content-type", "Application/x-java-serialized-object"); Sets the content type of the transfer to be a serializable Java object (if this is not set, the java.io.EOFException may be thrown when the serialized object is passed, when the Web service defaults to this type)
Connection.addrequestproperty ("Connection", "keep-alive");//set to remain connected to the server Connection.addrequestproperty (" Charset "," UTF-8 ");//Set character encoding type
Connect and send requests

Connect

Getoutputstream

Here Getoutstream will implicitly connect, so you can also not call connect

Get Response data

GetContent (https://my.oschina.net/zhanghc/blog/134591)

Getheaderfield: Get all response header fields

getInputStream

Geterrorstream: If the HTTP response indicates that an error was sent, getInputStream will throw a ioexception. Call Geterrorstream to read the error response.

Instance:

GET Request:

  

 Public Staticstring Get () {string message=""; Try{URL URL=NewURL ("http://www.baidu.com"); HttpURLConnection Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (5*1000);            Connection.connect (); InputStream InputStream=Connection.getinputstream (); byte[] Data=New byte[1024]; StringBuffer SB=NewStringBuffer (); intLength=0;  while(Length=inputstream.read (data))!=-1) {String s=NewString (data, Charset.forname ("Utf-8"));            Sb.append (s); } Message=sb.tostring ();            Inputstream.close ();        Connection.disconnect (); } Catch(Exception e) {e.printstacktrace (); }        returnmessage; }

POST request:

 

 Public Staticstring Post () {string message=""; Try{URL URL=NewURL ("http://119.29.175.247/wikewechat/Admin/Login/login.html"); HttpURLConnection Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("POST"); Connection.setdooutput (true); Connection.setdoinput (true); Connection.setusecaches (false); Connection.setconnecttimeout (30000); Connection.setreadtimeout (30000); Connection.setrequestproperty ("Content-type", "Application/x-javascript->json");            Connection.connect (); OutputStream OutputStream=Connection.getoutputstream (); StringBuffer SB=NewStringBuffer (); Sb.append ("Email="); Sb.append ("[Email protected]&]); Sb.append ("Password="); Sb.append ("1234&"); Sb.append ("Verify_code="); Sb.append ("4fj8"); String param=sb.tostring ();            Outputstream.write (Param.getbytes ());            Outputstream.flush ();            Outputstream.close (); LOG.D ("Ddddd", "responsecode" +Connection.getresponsecode ()); InputStream InputStream=Connection.getinputstream (); byte[] Data=New byte[1024]; StringBuffer SB1=NewStringBuffer (); intLength=0;  while(Length=inputstream.read (data))!=-1) {String s=NewString (data, Charset.forname ("Utf-8"));            Sb1.append (s); } Message=sb1.tostring ();            Inputstream.close ();        Connection.disconnect (); } Catch(Exception e) {e.printstacktrace (); }        returnmessage; }

Post upload pictures and form data:

public static String uploadfile (file file) {
String message= "";
String url= "http://119.29.175.247/uploads.php";
String boundary= "7786948302";
Map<string,string> params=new hashmap<> ();
Params.put ("name", "User");
Params.put ("Pass", "123");
try {
URL url1=new url (url);
HttpURLConnection connection= (httpurlconnection) url1.openconnection ();
Connection.setrequestmethod ("POST");
Connection.addrequestproperty ("Connection", "keep-alive");
Connection.addrequestproperty ("Charset", "UTF-8");
Connection.addrequestproperty ("Content-type", "multipart/form-data;boundary=" +boundary);
Set whether to output to httpurlconnection, because this is a POST request, the parameters to be placed in the
HTTP in the body, so it needs to be set to True, false by default;
Connection.setdooutput (TRUE);
Sets whether to read in from HttpURLConnection, true by default;
Connection.setdoinput (TRUE);
The Post request cannot use the cache?
Connection.setusecaches (FALSE);
Connection.setconnecttimeout (20000);
DataOutputStream dataoutputstream=new DataOutputStream (Connection.getoutputstream ());
FileInputStream fileinputstream=new fileinputstream (file);
Dataoutputstream.writebytes ("--" +boundary+ "\ r \ n");
Sets the content type of the transfer to be a serializable Java object
(If this item is not set, the java.io.EOFException may be thrown when the serialized object is passed, when the Web service defaults to this type)
Dataoutputstream.writebytes ("Content-disposition:form-data; Name=\ "File\"; Filename=\ ""
+ Urlencoder.encode (File.getname (), "UTF-8") + "\" \ \ r \ n ");
Dataoutputstream.writebytes ("\ r \ n");
Byte[] B=new byte[1024];
while ((Fileinputstream.read (b))!=-1) {
Dataoutputstream.write (b);
}
Dataoutputstream.writebytes ("\ r \ n");
Dataoutputstream.writebytes ("--" +boundary+ "\ r \ n");
try {
set<string > Keyset=params.keyset ();
for (String Param:keyset) {
Dataoutputstream.writebytes ("Content-disposition:form-data; Name=\ ""
+encode (param) + "\" \ \ "\ \ \ \");
Dataoutputstream.writebytes ("\ r \ n");
String value=params.get (param);
Dataoutputstream.writebytes (Encode (value) + "\ r \ n");
Dataoutputstream.writebytes ("--" +boundary+ "\ r \ n");

}
}catch (Exception e) {

}

InputStream Inputstream=connection.getinputstream ();
Byte[] Data=new byte[1024];
StringBuffer sb1=new StringBuffer ();
int length=0;
while ((Length=inputstream.read (data))!=-1) {
String S=new string (data, Charset.forname ("Utf-8"));
Sb1.append (s);
}
Message=sb1.tostring ();
Inputstream.close ();
Fileinputstream.close ();
Dataoutputstream.close ();
Connection.disconnect ();
} catch (Exception e) {
E.printstacktrace ();
}
return message;
}

private static string encode (string value) throws Unsupportedencodingexception {
return Urlencoder.encode (Value, "UTF-8");
}

Here we need to point out:

The header information that is captured through Chrome's development tools can be seen:

When uploading data via post, if you need to upload a file in addition to the text data, you need to specify the content-disposition,name of each piece of data, and if the file also indicates filename, it is separated by boundary after each transmission.

HttpURLConnection Basic Use

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.