Uses android network communication technology to directly transmit objects on the network

Source: Internet
Author: User
Tags network function

Reprinted please indicate the source: http://blog.csdn.net/guolin_blog/article/details/8967080

To be an excellent Android Application, network communication technology is essential. It is hard to imagine that a software without network interaction will eventually become much more successful. Let's take a look at how network interaction is generally implemented in Android applications. Here we take a boook object as an example:

As shown in, a book object is generated on the mobile phone end, which contains data such as the title, author, and price. To send the data to the server, We need to extract the data from the book object and assemble it into a string in XML format. Then, the assembled XML string is sent to the server through the Network API. When the server receives an XML string from the client, it must parse the XML. Then, reassemble the parsed data into a book object, and then the server can perform a series of other operations on the object.

Of course, the XML format has a large amount of data. Currently, many Android applications use JSON format to transmit data to save traffic. However, the steps described in XML and JSON are always indispensable.

I feel that using this method to transmit data is the most tedious process of encapsulating and parsing XML each time. Can I bypass this most complicated process?

As shown in, if you can call a Network API and directly send the book object to the server, the entire network interaction process will become very simple. Let's take a look at how to implement it.

Create an android project named clienttest as the client project. The first object to be determined here is the object to be transmitted. Let's create a book class with the Code as follows:

package com.test;import java.io.Serializable;public class Book implements Serializable {private String bookName;private String author;private double price;private int pages;public String getBookName() {return bookName;}public void setBookName(String bookName) {this.bookName = bookName;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public int getPages() {return pages;}public void setPages(int pages) {this.pages = pages;}}

This class is a simple pojo, but note that it implements the serializable interface. If you want to transmit an object over the network, the object must implement the serializable interface.

Next, open or create activity_main.xml as the main layout file of the program, and add the following code:

<Relativelayout 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: Background = "#000" tools: context = ". mainactivity "> <button Android: Id =" @ + ID/Send "Android: layout_width =" fill_parent "Android: layout_height =" wrap_content "Android: TEXT = "send"/> </relativelayout>

This layout contains a button. Click this button to send a network request.

Next, open or create mainactivity as the main activity of the program, and add the following code:

Public class mainactivity extends activity implements onclicklistener {private button send; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); send = (button) findviewbyid (R. id. send); send. setonclicklistener (this) ;}@ overridepublic void onclick (view v) {book = New Book (); book. setbookname ("android advanced programming"); book. setaut Hor ("Reto Meier"); book. set pages (398); book. setprice (59.00); Url url = NULL; objectoutputstream OOS = NULL; try {url = new URL ("http: // 192.168.1.103: 8080/servertest/servlet/testservlet "); httpurlconnection connection = (httpurlconnection) URL. openconnection (); connection. setdoinput (true); connection. setdooutput (true); connection. setconnecttimeout (10000); connection. setreadtimeout (10000); connection. setreques Tmethod ("Post"); OOS = new objectoutputstream (connection. getoutputstream (); OOS. writeobject (book); inputstreamreader READ = new inputstreamreader (connection. getinputstream (); bufferedreader BR = new bufferedreader (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 onclick method handles the click event. Here, a new book object is generated as the data to be transmitted, and a new URL object is generated, indicating the interface address on the server side, and configuring some optional parameters of httpurlconnection. Then, call the writeobject method of objectoutputstream to send the book object to the server, wait for the server to return data, and close the stream and connection.

Note that because we use the network function, we need to add the following permissions to androidmanifest. xml:

<uses-permission android:name="android.permission.INTERNET" />

Now, the android code has been developed. Now we are writing the server code.

Create a new web project named servertest. The first thing to do is to create a book class that is the same as that of Android under the WEB Project. It is very important to note that the book class on the server and the book class on the android end must have the same package name and class name; otherwise, a type conversion exception occurs. Here, because the content of the two book classes is exactly the same, I will not repeat them.

Create a new Java Servlet as the network access interface. We will rewrite its dopost method. The Code is as follows:

Public class testservlet extends httpservlet {public void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {objectinputstream OIS = NULL; try {OIS = new objectinputstream (request. getinputstream (); book = (book) Ois. readobject (); system. out. println ("name:" + book. getbookname (); system. out. println ("Author:" + book. getauthor (); system. out. println ("Price:" + book. getprice (); system. out. println ("page number:" + book. getpages (); printwriter out = response. getwriter (); out. print ("success"); out. flush (); out. close ();} catch (exception e) {e. printstacktrace ();} finally {Ois. close ();}}}

We can see that we first obtain the input stream by calling the getinputstream method of httpservletrequest, And Then assemble the input stream into an objectinputstream object. Next, it's easy to directly call the readobject method of objectinputstream, get the book object transmitted over the network, print the data carried in the book, and finally return success to the client.

Now let's run the program. First, deploy the servertest project on the server and enable server standby. Then open the clienttest application on your phone, as shown in:

Click send to send a network request. The server output is as follows:

The android end prints the following results:

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

Now, today's explanation is over. If you have any questions, please leave a message below.

Click here to download the source code

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