"You are my fixed, I am your passer-by." "------Android, here I come!"
The most commonly used HTTP request is nothing more than get and post,get requests can get static pages, you can also put the parameters behind the URL string, passed to Servlet,post and get the difference is that the post parameters are not placed in the URL string inside, Instead, it is placed inside the body of the HTTP request.
You can use HttpURLConnection to initiate both of these requests in Java, which is helpful for understanding soap and writing automated test code for Servlets.
The following code briefly describes how to use HttpURLConnection to initiate both requests, and the method of passing parameters:
public class Httpinvoker {
public static final String Get_url = "http://********";
public static final String Post_url = "http://********";
public static void Readcontentfromget () throws IOException {
Patchwork URL strings for Get requests, using Urlencoder.encode to encode special and invisible characters
String url= Get_url + "? account=" + ((Usermodel) Basemodel). GetUserName () + "&password=" + ((Usermodel) Basemodel). GetPassword ();
URL uri= new URL (URL);
Depending on the URL, the Url.openconnection function will open the connection, depending on the type of URL,
Returns an object of different urlconnection subclasses, where the URL is an HTTP, so the actual return is HttpURLConnection
HttpURLConnection connection = (httpurlconnection) URI
. OpenConnection ();
, but actually the GET request will be sent to the Connection.getinputstream () function in the next sentence.
Server
Connection.connect ();
Get the input stream and read it using reader
BufferedReader reader = new BufferedReader (New InputStreamReader (
Connection.getinputstream ()));
System.out.println ("=============================");
System.out.println ("Contents of Get Request");
System.out.println ("=============================");
String lines;
while ((lines = Reader.readline ()) = null) {
SYSTEM.OUT.PRINTLN (lines);
}
Reader.close ();
Disconnect Connection
Connection.disconnect ();
System.out.println ("=============================");
System.out.println ("Contents of Get Request Ends");
System.out.println ("=============================");
}
public static void Readcontentfrompost () throws IOException {
The URL of the POST request, unlike get, is not required with parameters
URL posturl = new URL (post_url);
Open connection
HttpURLConnection connection = (httpurlconnection) posturl
. OpenConnection ();
Output to the connection. Default is
False, set to True because post
Method must write something to the
Connection
Set whether to output to connection, 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
Connection.setdooutput (TRUE);
Read from the connection. Default is true.
Connection.setdoinput (TRUE);
Set the Post method. Default is GET
Connection.setrequestmethod ("POST");
Post cannot use caches
The Post request cannot use the cache
Connection.setusecaches (FALSE);
This method takes effects to
Every instances of this class.
Urlconnection.setfollowredirects is a static function that is used for all URLConnection objects.
Connection.setfollowredirects (TRUE);
This methods only
Takes Effacts to this
Instance.
Urlconnection.setinstancefollowredirects is a member function and is used only for the current function
Connection.setinstancefollowredirects (TRUE);
Set the content type to urlencoded,
Because we'll write
Some url-encoded content to the
Connection. Settings above must be set before connect!
Configure the Content-type of this connection, configured as application/x-www-form-urlencoded
This means that the text is urlencoded encoded form parameter, below we can see we use Urlencoder.encode for body content
to encode
Connection.setrequestproperty ("Content-type",
"application/x-www-form-urlencoded");
Connection, from Posturl.openconnection () to this point the configuration must be done before connect,
It is important to note that Connection.getoutputstream will implicitly connect.
Connection.connect ();
DataOutputStream out = new DataOutputStream (connection
. Getoutputstream ());
The url-encoded contend
Text, body content actually with get URL in '? ' After the argument string is consistent
String content = "Firstname=" + urlencoder.encode ("A Big Fat Man", "utf-8");
Dataoutputstream.writebytes writes a 16-bit Unicode character in a string as a 8-bit character in the stream
Out.writebytes (content);
Out.flush ();
Out.close (); Flush and close
BufferedReader reader = new BufferedReader (New InputStreamReader (
Connection.getinputstream ()));
String Line;
System.out.println ("=============================");
System.out.println ("Contents of Post request");
System.out.println ("=============================");
while (line = Reader.readline ()) = null) {
System.out.println (line);
}
System.out.println ("=============================");
System.out.println ("Contents of Post Request Ends");
System.out.println ("=============================");
Reader.close ();
Connection.disconnect ();
}
/** *//**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
try {
Readcontentfromget ();
Readcontentfrompost ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Above theThe Readcontentfromget () function produces a GET request that is passed to the servlet with a username parameter with the value "Fat Man".
The Readcontentfrompost () function produces a POST request to the servlet with a FirstName parameter, which is a value of "a Big Fat Man".
The Httpurlconnection.connect function, in effect, simply establishes a TCP connection to the server and does not actually send an HTTP request. Either the post or the get,http request actually untilHttpURLConnectionThe. getInputStream () function is only formally sent out.
InIn Readcontentfrompost (), the order is the most important, and all configuration of the connection object (that heap of set functions) must be done before the Connect () function executes. The write operation to OutputStream must be preceded by the InputStream read operation. These orders are actually determined by the format of the HTTP request.
The HTTP request actually consists of two parts, one is the HTTP header, and all the configuration about this HTTP request is defined in the HTTP header, one is the body content, in the Connect () function, HTTP headers are generated based on the configuration values of the HttpURLConnection object, so all configurations must be ready before calling the Connect function.
Immediately after the HTTP header is the body of the HTTP request, the content of the body is written by outputstream, in fact, OutputStream is not a network stream, at best, is a string stream, what is written to it will not be sent to the network immediately, but after the stream is closed, Generates an HTTP body based on what you enter.
At this point, the HTTP request is ready. When the getInputStream () function is called, the prepared HTTP request is formally sent to the server, and an input stream is returned to read the server's return information for this HTTP request. Since the HTTP request was sent out at getInputStream (including the HTTP header and the body), the connection object was set after the getInputStream () function (the information for the HTTP header was modified) or written OutputStream (Modifying the body) is meaningless, and performing these operations can cause an exception to occur.
The last section says that the outputstream of a POST request is actually not a network stream, but rather a write memory, in which the contents of the stream inside the getInputStream are really merged into a real HTTP request header based on the previous configuration. Request, and then actually send it to the server at this time.
The Httpurlconnection.setchunkedstreamingmode function can change this pattern, set the Chunkedstreamingmode, and no longer wait for the outputstream to close and generate the full HTTP The request sends the HTTP request header first, and the body content is transmitted to the server in real time by means of a network stream. In fact, it does not tell the length of the HTTP body of the server, which is suitable for transmitting to the server large or not easily accessible lengths of data, such as files.
public static void Readcontentfromchunkedpost () throws IOException {
URL posturl = new URL (post_url);
HttpURLConnection connection = (httpurlconnection) posturl
. OpenConnection ();
Connection.setdooutput (TRUE);
Connection.setdoinput (TRUE);
Connection.setrequestmethod ("POST");
Connection.setusecaches (FALSE);
Connection.setinstancefollowredirects (TRUE);
Connection.setrequestproperty ("Content-type",
"application/x-www-form-urlencoded");
/**//*
* Unlike Readcontentfrompost (), set the block size to 5 bytes
*/
Connection.setchunkedstreamingmode (5);
Connection.connect ();
/**//*
* Note that the following Getoutputstream function works in different ways in Readcontentfrompost ()
* in Readcontentfrompost () The function is still preparing the HTTP request, without sending any data to the server
* And here because the Chunkedstreamingmode,getoutputstream function is set according to the configuration before connect
* Generate HTTP request headers, which are sent to the server first.
*/
DataOutputStream out = new DataOutputStream (connection
. Getoutputstream ());
String params = "account=" + ((Usermodel) Basemodel). GetUserName () + "&password="
+ ((Usermodel) Basemodel). GetPassword ();
Outputstream.write (Params.getbytes ());
Out.flush ();
Out.close (); At this point the server has received the full HTTP request, and in the Readcontentfrompost () function, wait for the next server to receive HTTP requests.
BufferedReader reader = new BufferedReader (New InputStreamReader (
Connection.getinputstream ()));
Out.flush ();
Out.close (); Flush and close
String Line;
System.out.println ("=============================");
System.out.println ("Contents of Post request");
System.out.println ("=============================");
while (line = Reader.readline ()) = null) {
System.out.println (line);
}
System.out.println ("=============================");
System.out.println ("Contents of Post Request Ends");
System.out.println ("=============================");
Reader.close ();
Connection.disconnect ();
}
How to access Android Network (ii)---httpurlconnection