Android Network Programming (3)--Submit a request using URLConnection

Source: Internet
Author: User
Tags html header

The OpenConnection () method of the URL returns a URLConnection object that represents the communication connection between the application and the URL. A program can send a request to the URL through an URLConnection instance to read the resource referenced by the URL typically creating a connection to a URL and sending a request, reading the resource referenced by this URL requires the following steps
    1. Create a URLConnection object by calling the URL object OpenConnection () method
    2. Set parameters and normal request properties for URLConnection
    3. If you just send a Get method request, use Connect to establish an actual connection between the remote resources, and if you need to send a post-mode request, you need to get the output stream for the URLConnection instance to send the request parameters
    4. Remote resources become available, programs can access the header field of a remote resource, or read data from a remote resource through an input stream
Before establishing the actual connection to the remote resource, the program can set the request header field by the following method
    • setallowuserinteraction: Sets the value of the allowUserInteraction Request header field for this URLConnection
    • setdoinput: Sets the value of the Doinput Request header field for this URLConnection
    • setdooutput: Sets the value of the Dooutput Request header field for this URLConnection
    • setifmodifiedsince: Sets the value of the Ifmodifiedsince Request header field for this URLConnection
    • setusecaches: Sets the value of the Usecaches Request header field for this URLConnection
In addition, you can use the following methods to set or add a common header field
    • Setrequestproperty (string key, String value): Sets the value of the URLConnection key request header field, as shown in the following code:
Conn.setrequestproperty ("Accept", "*/*");
    • Addrequestproperty (string key, String value): Increases the value of the header field for the URLConnection key request, which does not overwrite the value of the original Request header field. Instead, the new value is appended to the original request header field
When a remote resource is available, the program can use the following methods to access the header fields and content
    • Object getcontent (): Gets the contents of the URLConnection
    • string Getheaderfield (string name): Gets the value of the specified response header field
    • getInputStream (): Returns the input stream corresponding to the URLConnection to get the contents of the URLConnection response
    • Getoutputstream (): Returns the urlconnection corresponding output stream used to send request parameters to URLConnection
If you want to use the input stream to read the contents of the URLConnection response, and also use the output stream to send the request parameters, be sure to use the output stream before using the input stream
The Getheaderfield () method is used to return the corresponding value based on the response header field. While some header fields often require access, all Java provides the following methods to access the value of a specific response header field
    • getcontentencoding: Gets the value of the Content-enconding response header field
    • getcontentlength: Gets the value of the Content-length response header field
    • getContentType: Gets the value of the Content-type response header field
    • getDate (): Gets the value of the Date response header field
    • getexpiration (): Gets the value of the Expires Response header field
    • getlastmodified (): Gets the value of the Last-modified response header field
category for URL requests: Divided into two categories, get and post requests. The difference is that: 1), get requests can get static pages, you can also put the parameters behind the URL string, passed to the servlet (using Java-written server program) 2), post and get different in the post parameters are not placed in the URL string, Instead, it is placed inside the body of the HTTP request. The POST request can transmit data to the server, and the data is sent to the server URL address together with the HTML header, and the data is not visible to the user. The get is to add the parameter data queue to the URL of the submission, the value and the form in each field one by one corresponding, for example (http://www.baidu.com/s?w=%C4&inputT=2710). Get request mechanism is used in the URL address inside, through? And then pass parameters to the client in the form of Name=value. Get transmits a small amount of data and cannot be greater than 2KB. Post transmits a large amount of data, which is generally not restricted by default. In theory, however, the maximum amount of IIS4 is 100KB in 80KB,IIS5. Get security is very low and post security is high.
Example: Submitting a request using URLConnection
androidmanifest.xml--main Add access network permissions
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.url_get_post "android:versioncode=" 1 "android:versionname=" 1.0 "> &LT;USES-SD K android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Android . permission. INTERNET "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_launcher "and Roid:label= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= "com . Example.url_get_post. Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> </application></manifest>
Activity_main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:gravity= "center"    android:orientation= "vertical"    tools:context= ". Mainactivity ">    <button         android:id=" @+id/get "        android:layout_width=" Wrap_content        " android:layout_height= "Wrap_content"                android:background= "#00ffff"        android:text= "get"/>    < Button         android:id= "@+id/post"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_ Content "         android:layout_margintop=" 40DP "              android:background=" #00ffff "        android:text=" post "/> </LinearLayout>
Getpostutil.java--get and post two ways to request
Package Com.example.url_get_post;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printwriter;import Java.net.malformedurlexception;import Java.net.URL; Import Java.net.urlconnection;import java.util.list;import Java.util.map;import Android.util.log;public class Getpostutil {/** * request to send a GET method to the specified URL * @param URL to send the request * @param the Parmas request parameter, the request parameter should be in the form of name1=value1&name2=value2 * @r Eturn the response of the remote resource represented by the URL */public static string sendget (string url, String parmas) {string result = ""; BufferedReader bufferedreader = null; String urlname = URL + "?" + parmas;try {URL realurl = new URL (urlname);//connection between open and URL try {urlconnection urlconnection = re Alurl.openconnection ();/* Sets the generic Request property *///tells the Web server what type of media to accept, */* represents any type, type/* represents all subtypes under that type, Type/sub-type. Urlconnection.setrequestproperty ("Accept", "*/*"), Urlconnection.setrequestproperty ("Connection", "keep-alive"); /browser indicates its identity (which browser) urlconnection.setrequestproperty ("User-agent", "mozilla/5.0 (Windows; UWindows NT 5.1; ZH-CN; rv:1.8.1.14);//Establish the actual connection urlconnection.connect (); LOG.E ("ContentType", "" +urlconnection.getcontenttype ()); LOG.E ("ContentLength", "" +urlconnection.getcontentlength ()); LOG.E ("ContentEncoding", "" +urlconnection.getcontentencoding ()); LOG.E ("Contentdate", "" "+urlconnection.getdate ());//Get all corresponding header fields map<string, list<string>> map = Urlconnection.getheaderfields ();//Traverse all response header fields for (String Key:map.keySet ()) {log.i ("Get-way Request", "" "+map.get (Key));} Defines the Bufferreader input stream to read the response of the URL BufferedReader = new BufferedReader (New InputStreamReader (Urlconnection.getinputstream ())); String line;for (;(line = Bufferedreader.readline ()) = null;) {result + = "\ n" + Line;}} catch (IOException e) {//TODO auto-generated catch blocklog.e ("Get Way Request", "Send Get Request Exception" +e); E.printstacktrace ();}} catch (Malformedurlexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {if (null! = Bufferedread ER) {try {bufferedreader.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.prinTstacktrace ();}}} return result;} /** * Request to send a POST method to the specified URL * @param URL to send the request * @param parmas request parameter, request parameter should be name1=value1&name2=value2 form * @return URL represented Remote resource response */public static string sendpost (string url, String parmas) {string result = ""; PrintWriter printwriter = null; BufferedReader BufferedReader = null;try {URL realurl = new URL (URL);//connection between open and URL try {urlconnection urlconnection = Realu Rl.openconnection ();//Set Generic request attribute Urlconnection.setrequestproperty ("accept", "*/*"); Urlconnection.setrequestproperty ("Connection", "keep-alive"); Urlconnection.setrequestproperty ("User-agent", " mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1);//The Send POST request must have the following two lines urlconnection.setdooutput (true); Urlconnection.setdoinput (true);//Get all corresponding header fields map< string, list<string>> map = Urlconnection.getheaderfields ();//Traverse all response header fields for (String Key:map.keySet ()) {LOG.I ( "Post mode Request", "" "+map.get (key)); Gets the output stream corresponding to the URLConnection object printwriter = new PrintWriter (Urlconnection.getoutputstream ());//Send request parameter Printwriter.print (ParMAS);//flush output stream buffer Printwriter.flush ();//define Bufferreader input stream to read the response of the URL BufferedReader = new BufferedReader (new InputStreamReader (Urlconnection.getinputstream ())); String line;for (;(line = Bufferedreader.readline ()) = null;) {result + = "\ n" + Line;}} catch (IOException e) {//TODO auto-generated catch blocklog.e ("Get Way Request", "Send Get Request Exception" +e); E.printstacktrace ();}} catch (Malformedurlexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {if (null! = Bufferedread ER) {try {bufferedreader.close ()} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (null! = PrintWriter) {printwriter.close ();}} return result;}}
mainactivity.java
Package Com.example.url_get_post;import Android.os.bundle;import Android.util.log;import android.view.View;import Android.widget.button;import Android.app.activity;public class Mainactivity extends Activity {private Button get,post;    Private String response;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);        get = (Button) This.findviewbyid (r.id.get);                Post = (Button) This.findviewbyid (r.id.post); Get.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method Stubnew Thread () {@Overridepublic void Run () {response = Getpostutil.sendget ("http://www.jju.edu.cn/", null); LOG.I ("response", response);};}.                Start ();}}); Post.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method Stubnew Thread () {@Overridepublic void run () {Response = Getpostutil.sendpost ("http://www.jju.edu.cn/", null),//LOG.I ("response", response);};}.    Start ();}}); }    }
Click the "Get" button, print the message and click the "POST" button to print the message.

Header field information is the same, for post occurrence of the exception, have not found the reason, first recorded. Here hope that the great God, pointing little brother me!!! Or because I use the website is my school's website, cannot write request?
Urlconnection.setdooutput (TRUE);//Use a URL connection for output urlconnection.setdoinput (TRUE);//enter using a URL connection
<strong> the following about creating a URLConnection object, establishing a connection process with the server </strong>:
from: http://www.cnblogs.com/shyang--TechBlogs/archive/2011/03/21/1990525.html
The first step is creat:urlconnection Urlconnect = Url.openconnection ();The second step is connect:urlConnection.connect ();//These two are different. some variable options (such as setdoinput, timeouts, etc.) can be set between created and connected, and an exception will be thrown if the connect is set again actions that require a connection (such as application-level actions such as getInputStream), the program will secretly (implicitly) perform the connection。 Once the connection is available, access to resources such as execution getInputStream () and, for Httpurlconnect, Conn. Getresponsecode () ==200 to determine if the server returned the correct answer code to indicate that the request was accepted. In URLConnection, there is a domain Boolean connected, and a value of TRUE indicates that a connection has been established to the specified URL, and false is not. Connect () When the connection is not established, open a communications link, and if the link is already open (connect value is set to true), ignore it
URL url = new URL ("http://www.google.cn"); URLConnection conn = Url.openconnection (); Conn.setconnecttimeout (10000); Conn.connect (); InputStream InStream = Conn.getinputstream ();
when execution finishes executing openconnection (), the domain connected value is still false, indicating that it is not connected at this time. After execution to connect (), the connected becomes true, indicating that the connection is complete. After commenting out connect (), after running the program, the connected value to getInputStream executes and becomes True,getinputstream secretly performs the connection.


Android Network Programming (3)--Submit a request using URLConnection

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.