Transferred from: http://wang09si.blog.163.com/blog/static/1701718042013631104658130/
JAVA HttpURLConnection Post method submission Pass parameters
Package wzq.j2se;
Import Java.io.BufferedReader;
Import Java.io.DataOutputStream;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.net.URLEncoder;
public class Httpurlconnectionpost {
/**
* @param args
* @throws IOException
*/
public static void Main (string[] args) throws IOException {
Readcontentfrompost ();
}
public static void Readcontentfrompost () throws IOException {
The URL of the POST request, unlike get, is not required with parameters
URL posturl = new URL ("http://www.wangzhiqiang87.cn");
Open connection
HttpURLConnection connection = (httpurlconnection) posturl.openconnection ();
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);
The default is Get mode
Connection.setrequestmethod ("POST");
The Post request cannot use the cache
Connection.setusecaches (FALSE);
Connection.setinstancefollowredirects (TRUE);
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 = "account=" + urlencoder.encode ("A Big Fat Man", "UTF-8");
Content + = "&pswd=" +urlencoder.encode ("Two big fat people", "UTF-8");;
Dataoutputstream.writebytes writes 16-bit Unicode characters in a string to the stream as a 8-bit character
Out.writebytes (content);
Out.flush ();
out.close ();
BufferedReader reader = new BufferedReader (New InputStreamReader (Connection.getinputstream ()));
String Line;
while (line = Reader.readline ())! = null) {
System.out.println (line);
}
reader.close ();
Connection.disconnect ();
}
}
At the receiving end, this gets the parameters:
String name = Request.getparameter ("account");
String pswd = Request.getparameter ("pswd");
System.out.println (New String (Name.getbytes ("iso-8859-1"), "UTF-8"));
System.out.println (New String (Pswd.getbytes ("iso-8859-1"), "UTF-8"));
JAVA HttpURLConnection Post method submission Pass parameters