Android stream-based XML Data Transmission

Source: Internet
Author: User

 

We can send data to the server in the form of Request Parameters. However, when the data size is too large, this method is unavailable. At this time, we should send data in a stream mode, in the following example, the content of an xml file is sent to the server as a byte stream.

 

1. Create a new web project. Because struts2 is used, you need to introduce relevant jar packages and configure the corresponding environment.

2. Create an action

Java code

Package com. lamp. action;

 

Import java. io. ByteArrayOutputStream;

Import java. io. InputStream;

 

Import javax. servlet. http. HttpServletRequest;

 

Import org. apache. struts2.ServletActionContext;

 

Public class XMLDataAction {

// Obtain the byte array through the input stream

Public static byte [] readStream (InputStream is) throws Exception {

Byte [] buffer = new byte [1024];

ByteArrayOutputStream bos = new ByteArrayOutputStream ();

Int len = 0;

While (len = is. read (buffer ))! =-1 ){

Bos. write (buffer, 0, len );

}

Is. close ();

Return bos. toByteArray ();

}

Public String execute () throws Exception {

// Obtain the HttpServletRequest object

HttpServletRequest request = ServletActionContext. getRequest ();

// Obtain the input stream from the client

InputStream is = request. getInputStream ();

Byte [] data = readStream (is );

String str = new String (data, "UTF-8 ");

If (str! = Null ){

System. out. println (str );

Return "success ";

}

Return "error ";

}

}

 

 

3. configure action in struts. xml

Xml Code

<Package name = "lamp" extends = "struts-default">

<Action name = "XMLData" class = "com. lamp. action. XMLDataAction">

<Result name = "success">/WEB-INF/page/success. jsp </result>

<Result name = "error">/WEB-INF/page/error. jsp </result>

</Action>

</Package>

 

 

4. Create an Android project and write a tool class to send data streams to the server.

Java code

Package com. lamp. util;

 

Import java. io. ByteArrayOutputStream;

Import java. io. DataOutputStream;

Import java. io. InputStream;

Import java.net. HttpURLConnection;

Import java.net. URL;

 

Public class NetTool {

// Send xml file data to the server in stream mode and obtain the server output stream

Public static InputStream sendXMLData (String urlPath, byte [] data, String encoding) throws Exception {

URL url = new URL (urlPath );

// Open the connection

HttpURLConnection conn = (HttpURLConnection) url. openConnection ();

// Set the submission method

Conn. setDoOutput (true );

Conn. setDoInput (true );

Conn. setRequestMethod ("POST ");

// Cache cannot be used in post Mode

Conn. setUseCaches (false );

Conn. setInstanceFollowRedirects (true );

// Set the connection timeout

Conn. setConnectTimeout (6*1000 );

// Configure the Content-Type for this connection

Conn. setRequestProperty ("Content-Type", "text/html; charset = UTF-8 ");

// Maintain persistent connections

Conn. setRequestProperty ("Connection", "Keep-Alive ");

// Sets the browser encoding.

Conn. setRequestProperty ("Charset", "UTF-8 ");

DataOutputStream dos = new DataOutputStream (conn. getOutputStream ());

// Send request parameter data to the server

Dos. write (data );

Dos. flush ();

Dos. close ();

If (conn. getResponseCode () = 200 ){

// Obtain the server output stream

Return conn. getInputStream ();

}

Return null;

}

// Obtain the byte array through the input stream

Public static byte [] readStream (InputStream is) throws Exception {

Byte [] buffer = new byte [1024];

ByteArrayOutputStream bos = new ByteArrayOutputStream ();

Int len = 0;

While (len = is. read (buffer ))! =-1 ){

Bos. write (buffer, 0, len );

}

Is. close ();

Return bos. toByteArray ();

}

}

 

 

5. Compile a test class to test it.

Java code

Package com. lamp. activity;

 

 

Import java. io. File;

Import java. io. FileInputStream;

Import java. io. FileNotFoundException;

Import java. io. InputStream;

Import android. OS. Environment;

Import android. test. AndroidTestCase;

Import android. util. Log;

 

Import com. lamp. util. NetTool;

 

Public class TestPostData extends AndroidTestCase {

Private static final String TAG = "TestPostData ";

// Send data to the server as a stream

Public void testSendXML () throws Exception {

String urlPath = "http: // ip: 8080/TestAndroid/XMLData ";

// Read The persons. xml file from the sdk card

File file = new File (Environment. getExternalStorageDirectory (), "persons. xml ");

InputStream is = new FileInputStream (file );

Byte [] data = NetTool. readStream (is );

Is = NetTool. sendXMLData (urlPath, data, "UTF-8 ");

Data = NetTool. readStream (is );

Log. I (TAG, new String (data ));

}

 

}

 

 

6. Remember to register network access permissions and configurations required for unit testing in the AndroidManifest. xml file.

Xml Code

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

 

 

Finally, run the web Project and run the unit test class. We can see that the server prints the data transmitted by the client.

Author: "sitting like a pine, moving like a wind"

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.