Android uses HttpURLConnection to send java serialized objects through POST, and netty sends serialized objects

Source: Internet
Author: User

Android uses HttpURLConnection to send java serialized objects through POST, and netty sends serialized objects

Using the HttpURLConnection class, you can not only send strings to WebService, but also send serialized java objects to achieve data interaction between Android phones and servers.

Android code:

1 public String SendDataByPost (String urlStr) {2 URL = null; 3 String result = ""; // the result to be returned 4 try {5 url = new url (urlStr ); 6 HttpURLConnection httpURLConnection = (HttpURLConnection) url. openConnection (); 7 8 httpURLConnection. setConnectTimeout (2000); // sets the connection timeout time, in the unit of ms 9 httpURLConnection. setReadTimeout (2000); // set the read timeout value, in ms10 11. // set whether to output data to httpURLConnection. Because the post request parameter must be placed in the http body, set it to true12 httpURLConn. Ection. setDoOutput (true); 13 14 // sets whether to read data from httpURLConnection. The default value is false15 httpURLConnection. setDoInput (true); 16 17 // the POST request cannot be cached and is set to false18 httpURLConnection. setUseCaches (false); 19 20 // The transmitted content is serializable 21 // If this option is not set, when the serialization object is transmitted, when the WEB service is not of this type by default, will throw java. io. EOFException error 22 httpURLConnection. setRequestProperty ("Content-type", "application/x-java-serialized-object"); 23 24 // set the request method to POST25 httpURLConnection. setReques TMethod ("POST"); 26 27 // connection server 28 httpURLConnection. connect (); 29 30 // getOutputStream implicitly calls connect (), so you do not need to write the above httpURLConnection. connect. 31 // get the output stream of httpURLConnection 32 OutputStream OS = httpURLConnection. getOutputStream (); 33 34 // construct the output stream object to achieve output serialization. Object 35 ObjectOutputStream objOut = new ObjectOutputStream (OS ); 36 37 // The dataPost class is a custom data interaction object with only two member variables 38 dataPost data = new dataPost ("Tom", null ); 39 40 // write data to the output stream of the object, which will be stored in the memory buffer 41 objOut. writeObject (data); 42 43 // refresh the object output stream and write all bytes to the output stream 44 objOut. flush (); 45 46 // close Stream object 47 objOut. close (); 48 OS. close (); 49 50 // send the complete HTTP Request Message encapsulated in the memory buffer to the server and obtain the access status 51 if (HttpURLConnection. HTTP_ OK = httpURLConnection. getResponseCode () {52 53 // get the input stream of httpURLConnection, which contains the java object 54 InputStream in = httpURLConnection returned by the server. getInputStream (); 55 56 // construct the object input stream. Use the readObject () method to retrieve the java object 57 ObjectInputStream inObj = new ObjectInputStream (in); 58 data = (dataPost) inObj in the input stream. readObject (); 59 60 // retrieve the data in the object 61 result = data. password; 62 63 // output Log. You can view the received data 64 Log on the console. w ("HTTP", result + ": by post"); 65 66 // close the created stream 67 in. close (); 68 inObj. close (); 69} else {70 Log. w ("HTTP", "Connction failed" + httpURLConnection. getResponseCode (); 71} 72} catch (Exception e) {73 e. printStackTrace (); 74} 75 return result; 76}
1 package com.example.com. example. data; 2 3 import java. io. Serializable; 4 5 // implement the Serializable interface to make dataPost Serializable. 6 public class dataPost implements Serializable {7 8/* specifies the serialization version number to ensure the consistency of the serialization version. On the server side, the JVM compares the 9 serialVersionUID of the byte stream sent with the serialVersionUID of the corresponding local object (class). If the value is the same, 10 is the same, deserialization is supported. Otherwise, the serialization version is inconsistent. */11 private static final long serialVersionUID = 1L; 12 13 String name; 14 String password; 15 public dataPost (String name, String password) {16 this. name = name; 17 this. password = password; 18} 19 20 public String getName () {21 return name; 22} 23 24 public void setName (String name) {25 this. name = name; 26} 27 28 public String getPassword () {29 return password; 30} 31 32 public void setPassword (String password) {33 this. password = password; 34} 35 36}

Server program:

 1 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2          3         ServletInputStream in=request.getInputStream(); 4         dataPost datap = null; 5         ObjectInputStream obj=new ObjectInputStream(in); 6         try { 7             datap= (dataPost) obj.readObject(); 8         } catch (ClassNotFoundException e) { 9             e.printStackTrace();10         }finally{11             obj.close();12 13         }                14         response.setContentType("application/x-java-serialized-object");15         OutputStream out=response.getOutputStream();16         ObjectOutputStream outObj=new ObjectOutputStream(out);17         datap.setPassword("9964646");18         outObj.writeObject(datap);19         outObj.flush();20         outObj.close();21     }
Note: 1. If the client url contains Chinese characters, garbled characters are displayed. You need to encode the url.

For example:

1 String url = "hello"; 2 URI uri = new URI (url, false, "UTF-8"); 3 url = uri. toString ();
2. When the SendDataByPost () method is called in the Android main program, re-open a thread; otherwise, the main thread will be blocked.

 

 1 new Thread(new Runnable() { 2             @Override 3             public void run() { 4                 HTTPURLConnectionGETData getData = new HTTPURLConnectionGETData(); 5                 String result=getData.SendStringDataByPost(serverIP1); 6                 if("".equals(result)){ 7                 }else{ 8                     Log.i("HTTP",result); 9                 }10             }11         }).start();

 

3. The package name of the Android-side dataPost class must be the same as that of the server-side dataPost package. Otherwise, the exception of this class cannot be found.

Java. lang. ClassNotFoundException: com.example.com. example. data. dataPost

At org. apache. catalina. loader. WebappClassLoaderBase. loadClass (WebappClassLoaderBase. java: 1333)

4. The package name of the Android-side dataPost class must be consistent with the serialized version of The dataPost on the server side. Otherwise, different serialVersionUID errors will be reported.

Servlet. service () for servlet [com. test. stream. testStream] in context with path [/campus2] threw exception

Java. io. InvalidClassException: com.example.com. example. data. dataPost; local class incompatible:

Stream classdesc serialVersionUID =-1197271749879367300, local class serialVersionUID =-3085829960977977003

Solution:

Explicitly specifying the serialization version number in the dataPost class at both ends is generally achieved by adding private static final long serialVersionUID = 1L.

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.