Use HttpURLConnection to transfer objects between the android client and the server

Source: Internet
Author: User

Use HttpURLConnection to transfer objects between the android client and the server

Generally, json and XML are used for data interaction between the client and the server. Compared with XML, json is more lightweight and saves traffic. However, whether json or xml is used, we need to encapsulate the data into a json string or an xml string before transmission. Is it possible that we directly pass an Object to the server on the android client? The answer is yes.

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

When we click the register button, we will pass the user's registration information to the server through an Object. Well, let's take a look at how to transfer the Object:

First, we need to encapsulate the user registration information into a JavaBean. To ensure that this JavaBean can be transmitted over the network, we need to implement the Serializable interface:

 

public class Person implements Serializable {/** *  */private static final long serialVersionUID = 1L;private String password;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 = username;this.nickname = nickname;}public Person() {}}

When you click the register button, encapsulate the user registration information, and then use an AsyncTask to execute the network request. The AsyncTask parameter is the Bean encapsulated by the user registration information:

 

 

TransObject to = new TransObject();to.execute(new Person(passwd.getText().toString(), name.getText().toString(), nickname.getText().toString()));

Okay. Let's take a look at the TransObject class:

 

 

Class TransObject extends AsyncTask
 
  
{@ 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 to allow output. The default value is falsecon. setDoOutput (true); con. setConnectTimeout (5*1000); con. setReadTimeout (10*1000); // The Request Method is POST request con. setRequestMethod (POST); oos = new ObjectOutputStream (con. getOutputStream (); // write data to the server oos. writeObject (p); // get the data returned by 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, registration successful, Toast. LENGTH_SHORT). show ();}}}
 
We execute our network request in doInBackground, output our object to the server through an object output stream, then return the request result to the onPostExecute method, and determine whether the registration is successful in onPostExecute. This is the client writing method. Let's look at the server writing method:

 

 

@ WebServlet (/to) public class TransObject extends HttpServlet {private static final long serialVersionUID = 1L; public TransObject () {} protected void doGet (HttpServletRequest request, response) throws ServletException, IOException {System. out. println (doGet);} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System. o Ut. println (doPost); ObjectInputStream ois = new ObjectInputStream (request. getInputStream (); try {Person p = (Person) ois. readObject (); System. out. println (password: + p. getPassword (); System. out. println (username: + p. getUsername (); System. out. println (Nickname: + p. getNickname (); PrintWriter out = response. getWriter (); out. print (OK); out. flush (); out. close ();} catch (ClassNotFoundException e) {e. printStackTrace ();} fi Nally {if (ois! = Null) {ois. close ();}}}}

On the server side, we use a Servlet to receive data from the client. In the doPost method, we use ObjectInputStream to receive objects sent from android. After obtaining the Person object, we print out the values, return an OK message to the client. Note that the Person class on the server must be the same as the Person class on the client (including the package name); otherwise, an exception occurs, such:

 

 

After the above steps, we can pass an Object of the android client to the server. This is simple and saves the trouble of converting an Object into json or XML.

 

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.