In Java, it is common for a background server to send requests directly using Java Network programming, or using HttpClient to send HTTP requests back to the server side. Although all Java APIs can be used in Android, but HttpClient is not a problem, after all, it is a Java standard implementation of a class, in Android, want to connect the backend server, specifically based on Android to implement a class, For HttpURLConnection. With HttpURLConnection, we can implement sending HTTP requests to the server, connecting the backend server and the client.
These days are just doing Android client and server-side communication, using the HttpURLConnection.
HttpURLConnection can implement a request for a full HTTP protocol.
First, new a URL that knows the address of the connection server.
1 New URL (appsdata.loginserverurl); 2 httpurlconnection httpurlconnection = (httpurlconnection) url.openconnection ();
Where Appsdatah.loginserverurl is set to a URL.
The next step is to set the contents of the HTTP protocol:
1 // set the HTTP protocol 2 Httpurlconnection.setrequestmethod ("POST"); 3 httpurlconnection.setdooutput (true); 4 httpurlconnection.setdoinput (true); 5 httpurlconnection.setconnecttimeout (); 6 httpurlconnection.setrequestproperty ("Content-type", "Application/x-java-serialized-object");
Next, as with normal network programming, use the stream to write the content:
1 outputstream outputstream = httpurlconnection.getoutputstream (); 2 New ObjectOutputStream (outputstream); 3 4 New StringBuffer (); 5 stringbuffer.append (Data); 6 7 Objectoutputstream.writeobject (StringBuffer);
At the end must remember to use the Flush method, when this method is used when the data is actually sent successfully, but this method must be placed at the end of the above settings to be effective.
1 Objectoutputstream.flush (); 2 httpurlconnection.getinputstream ();
The data can be sent through the above method.
However, it is worth noting that after Android 3.0, if you want to send a request to the background, or to establish a connection, if you call this method directly, the program will error.
The reason is: when the main program in the background to send the request, not necessarily will be sent to, if not sent to, the main program will always wait for the response, but the sample program will not be able to do other things, it seems that the program is very "card", Android to prevent this from happening will be in the main thread request connection process set to an exception, here we can use multi-threaded way to send requests in the background, each send a request to the background, create a thread in the program, does not affect the main thread running.
It is also important to note that once a thread has finished running, it is possible to start the thread again, but it is cumbersome, so it is recommended that another thread be created again upon request.
The Android client connects to the server side and sends a request to the server HttpURLConnection