Skillfully use Android network communication technology to transfer objects directly on the network

Source: Internet
Author: User

This article starts in CSDN blog, reprint please indicate source:

To be a good Android app, using network communication technology is essential, and it's hard to imagine how successful a software without network interaction can ultimately develop. So let's take a look at how the general Android app interacts with the Web, and here's an example of a Boook object:

As shown, first create a book object on the phone, which contains the title, author, price and other data. In order to send this data to the server side, we take the data out of the book object and assemble it into an XML-formatted string. Then, through the network API, the assembled XML string is sent to the server side. The server is connected to the XML string sent by the client, and the XML must be parsed. Then the parsed data is reassembled into a book object, and then the server can perform a series of other operations on the object.

Of course, the amount of data in XML format is large, and many Android applications now use JSON format to transfer data in order to save traffic. However, whether you use XML or JSON, the steps described in are always unavoidable.

It feels like using this method to transfer data, each time the process of encapsulating and parsing XML is the most tedious, can you bypass the most tedious process?

As shown, if you can call the network API, directly send the book object to the server side, then the entire network interaction process will become very simple, let's see how to implement.

Create a new Android project named Clienttest as the client project. The first thing to determine is the object to be transferred, we create a new book class, the code is as follows:

 Packagecom.test;; Public classBookImplementsSerializable {PrivateString BookName; PrivateString author; Private DoublePrice ; Private intpages;  PublicString Getbookname () {returnBookName; }     Public voidsetbookname (String bookname) { This. BookName =BookName; }     PublicString Getauthor () {returnauthor; }     Public voidSetauthor (String author) { This. Author =author; }     Public DoubleGetPrice () {returnPrice ; }     Public voidSetprice (DoublePrice ) {         This. Price =Price ; }     Public intgetpages () {returnpages; }     Public voidSetpages (intpages) {         This. Pages =pages; }}

This class is a simple pojo, but note that it implements the serializable interface, and if you want to transfer objects on the network, then the object must implement the Serializable interface.

Next open or new Activity_main.xml as the program's main layout file, add the following code:

<Relativelayoutxmlns:android= "Http://"Xmlns:tools= "Http://"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:background= "#000"Tools:context=". Mainactivity " >   <ButtonAndroid:id= "@+id/send"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Send"     /></Relativelayout>

This layout contains a button, click on the button to make a network request.

Next open or new mainactivity as the main activity of the program, which includes the following code:

 Public classMainactivityextendsActivityImplementsOnclicklistener {PrivateButton Send; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Send=(Button) Findviewbyid (; Send.setonclicklistener ( This); } @Override Public voidOnClick (View v) { Book Book=NewBook (); Book.setbookname ("Android Advanced Programming"); Book.setauthor ("Reto Meier"); Book.setpages (398); Book.setprice (59.00); URL URL=NULL; ObjectOutputStream Oos=NULL; Try{URL=NewURL ("Http://"); HttpURLConnection Connection=(HttpURLConnection) url.openconnection (); Connection.setdoinput (true); Connection.setdooutput (true); Connection.setconnecttimeout (10000); Connection.setreadtimeout (10000); Connection.setrequestmethod ("POST"); Oos=NewObjectOutputStream (Connection.getoutputstream ());            Oos.writeobject (book); InputStreamReader Read=NewInputStreamReader (Connection.getinputstream ()); BufferedReader BR=NewBufferedReader (read); String Line= "";  while(line = Br.readline ())! =NULL) {LOG.D ("TAG", "line is" +Line );            } br.close ();        Connection.disconnect (); } Catch(Exception e) {e.printstacktrace (); } finally {        }    }}

We can see that the click event of the button is handled in the OnClick method. Here first a book object is created as the data to be transferred, then a new URL object is created, which indicates the server-side interface address, and then configures some optional parameters of httpurlconnection. Then, by calling ObjectOutputStream's WriteObject method, the book object is sent to the server side, and then the server side returns the data, and finally closes the stream and connection.

Note Because we are using network functionality, we need to include the following permissions in Androidmanifest.xml:

<android:name= "Android.permission.INTERNET"/>

Well, now that the Android code has been developed, we are now ready to write server-side code.

Create a new Web project named Servertest, and the first thing to do is to create a book class like Android on the Web project. Here's a very important point. We must note that the server-side book class and the Android side of the book class, the package name and class names must be the same, or a type conversion exception will occur. Since the contents of the two book classes are exactly the same, I will not repeat the post.

Then create a new Java servlet as a network access interface, and we rewrite its Dopost method with the following code:

 Public classTestservletextendsHttpServlet { Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {objectinputstream ois=NULL; Try{ois=NewObjectInputStream (Request.getinputstream ()); Book Book=(book) Ois.readobject (); System.out.println ("The title is:" +book.getbookname ()); System.out.println ("The author is:" +Book.getauthor ()); System.out.println ("Price is:" +Book.getprice ()); System.out.println ("pages are:" +book.getpages ()); PrintWriter out=Response.getwriter (); Out.print ("Success");            Out.flush ();        Out.close (); } Catch(Exception e) {e.printstacktrace (); } finally{ois.close (); }    }    }

As you can see, we first get to the input stream by calling HttpServletRequest's getInputStream method, and then assemble the input stream into a ObjectInputStream object. The next step is simply to call ObjectInputStream's ReadObject method, get the book object transmitted over the network, print out the data carried in the book, and finally return the success to the client.

Now let's run the program, first servertest the project to the server, and open the server standby. Then open clienttest This application on the phone, as shown in:

Click Send to make a network request, you can see the server-side printing results are as follows:

The results of the Android print are as follows:

From this we can see that the transmission of the object on the network has been successful! Without tedious XML encapsulation and parsing, we have successfully sent the data in the book completely from the Android to the server side.

Well, today's explanation to this end, a friend in doubt please leave a message below.

SOURCE download, please click here

Skillfully use Android network communication technology to transfer objects directly on the network

Related Article

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: 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.