Using HttpURLConnection to deliver objects between Android clients and servers

Source: Internet
Author: User
Tags gettext

In general, the client and server data interaction is using JSON and XML, compared to Xml,json is more lightweight, and save traffic, however, whether we use JSON or XML, we need to first encapsulate the data into a JSON string or an XML string and then transfer, So is it possible for us to pass an object to the server side directly on the Android client? The answer is yes.

Let's look at a simple app registration page, such as:


When we click the Register button, we pass the user's registration information to the server via an object, OK, let's see how to pass the object:

First we need to encapsulate the user's registration information into a javabean, for this javabean can be transmitted over the network, we want to implement the Serializable interface:

public class Person implements Serializable {/** *  */private static final long serialversionuid = 1l;private String pa Ssword;private string Username;private string Nickname;public string GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String Getnickname () {return nickname;} public void Setnickname (String nickname) {this.nickname = nickname;} Public person (string password, string username, string nickname) {super (); This.password = Password;this.username = Userna Me;this.nickname = nickname;} Public person () {}}

When we click the Register button, we first encapsulate the user's registration information and then use a asynctask to execute the network request, the Asynctask parameter is the bean that the user registration information encapsulates:

Transobject to = new Transobject (); To.execute (New Person (Passwd.gettext (). ToString (), Name.gettext (). ToString (), Nickname.gettext (). toString ());

OK, let's take a look at Transobject this class:

Class Transobject extends Asynctask<person, Void, string> {@Overrideprotected String doinbackground (Person ... params) {StringBuffer sb = new StringBuffer (); Person p = params[0]; BufferedReader reader = null;  HttpURLConnection con = null;objectoutputstream oos = null;try {URL url = new URL ("http://192.168.1.106/android/to"); con = (httpurlconnection) url.openconnection ();//set allow output, default is Falsecon.setdooutput (true); Con.setconnecttimeout (5 * 1000); Con.setreadtimeout (10 * 1000);//Request mode for POST request Con.setrequestmethod ("post"); Oos = new ObjectOutputStream ( Con.getoutputstream ());//write data to the server Oos.writeobject (p);//Get the return data of the server InputStreamReader read = new InputStreamReader ( Con.getinputstream ()); reader = new BufferedReader (read); String line = "", while (line = Reader.readline ())! = null) {sb.append (line);}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if (reader!) = null) {try {reader.close ();} catch (IOException e) {e.printstacktrace ()}} if (oOS = null) {try {oos.close ();} catch (IOException e) {e.printstacktrace ()}} if (con! = null) {Con.disconnect ();}} return sb.tostring ();} @Overrideprotected void OnPostExecute (String result) {Super.onpostexecute (result); if (result! = null && "OK". Equals (Result) {Toast.maketext (Mainactivity.this, "registered successfully", Toast.length_short). Show ();}}
We execute our network request in Doinbackground, output our object to the server through an object output stream, and then return the request result to the OnPostExecute method, in OnPostExecute to determine whether the registration was successful. This is the client's wording, and we look at the service side of the wording:

@WebServlet ("/to") public class Transobject extends HttpServlet {private static final long Serialversionuid = 1l;public Tra NSObject () {}protected void doget (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException {System.out.println ("Doget");} protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException { System.out.println ("DoPost"); ObjectInputStream ois = new ObjectInputStream (Request.getinputstream ()); try {person P = ( person) Ois.readobject (); SYSTEM.OUT.PRINTLN ("Password is:" + P.getpassword ()); System.out.println ("User name is:" + p.getusername ()); System.out.println ("nickname is:" + p.getnickname ()); PrintWriter out = Response.getwriter (); Out.print ("OK"); Out.flush (); Out.close ();} catch (ClassNotFoundException e) {e.printstacktrace ();} finally {if (OIS! = null) {Ois.close ();}}}}

On the server we use a servlet to receive data from the client, and in the Dopost method we use ObjectInputStream to receive the object from Android, and after we get the person object, we print out the values. Returns a OK to the client at the same time. One thing to note here is that the person class on the server is exactly the same as the client class (including the package name), otherwise there will be exceptions such as:



Well, after a few steps, we can pass an object from the Android client to the server, which is as simple as eliminating the hassle of converting objects to JSON or XML.

Android Demo Download HTTPS://GITHUB.COM/LENVE/TRANSOBJ

Service Side Demo Download http://download.csdn.net/detail/u012702547/9263967

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. If there is a wrong place, I would appreciate it if I could criticize it.

Using HttpURLConnection to deliver objects between Android clients and servers

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.