Android HttpClient file upload and Httpconnection knowledge

Source: Internet
Author: User

Android can upload files to the server using HttpConnection or the HttpClient class encapsulated by Android. It is convenient and convenient to use httpconnection to upload files only.

 

1. Use HttpConection to upload files. Converts a file to a form data stream. The main idea is to construct an http protocol, and the server parses the packets to obtain form data. Code snippet:

 

[Java]

HttpURLConnection con;

Try {

Con = (HttpURLConnection) url. openConnection ();

Con. setConnectTimeout (C_TimeOut );

/* Allow Input and Output without using Cache */

Con. setDoInput (true );

Con. setDoOutput (true );

Con. setUseCaches (false );

/* Set the transfer method = POST */

Con. setRequestMethod ("POST ");

/* SetRequestProperty */

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

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

Con. setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + boundary );

/* Set DataOutputStream */

DataOutputStream ds = new DataOutputStream (con. getOutputStream ());

FileInputStream fStream = new FileInputStream (file );

 

/* Set 1024 bytes for each write */

Int buffer size = 1024;

Byte [] buffer = new byte [bufferSize];

 

Int length =-1;

/* Read data from the file to the buffer */

While (length = fStream. read (buffer ))! =-1)

{

/* Write data to DataOutputStream */

Ds. write (buffer, 0, length );

}

FStream. close ();

Ds. flush ();

Ds. close ();

 

Refer

 

① Achieve Image Upload by simulating HTTP multipart/form-data Request protocol information on Android ② 3 methods for android Http access and upload

 

2. Use the Android HttpClient class to upload parameters. I found the code on the Internet and forgot the source.

 

 

[Java]

Private static boolean sendPOSTRequestHttpClient (String path,

Map <String, String> params) throws Exception {

// Encapsulate Request Parameters

List <NameValuePair> pair = new ArrayList <NameValuePair> ();

If (params! = Null &&! Params. isEmpty ()){

For (Map. Entry <String, String> entry: params. entrySet ()){

Pair. add (new BasicNameValuePair (entry. getKey (), entry

. GetValue ()));

}

}

// Change the request parameter to the Request body

UrlEncodedFormEntity uee = new UrlEncodedFormEntity (pair, "UTF-8 ");

// Use the HttpPost object to set the URL path to be sent

HttpPost post = new HttpPost (path );

// Send the request body

Post. setEntity (uee );

// Create a browser object to send the POST object to the server and return the Response Message.

DefaultHttpClient dhc = new DefaultHttpClient ();

HttpResponse response = dhc.exe cute (post );

If (response. getStatusLine (). getStatusCode () = 200 ){

Log. I ("http", "httpclient ");

Return true;

}

Return false;

}

 

3. Use httpClient to upload text and file information. It is very convenient to use httpClient to upload files. However, you need to import two. jar packages, apache-mime4j-0.6.jar and httpmime-4.0.jar.

 

[Java]

// Encapsulate Request Parameters

MultipartEntity mpEntity = new MultipartEntity ();

If (params! = Null &&! Params. isEmpty ()){

For (Map. Entry <String, String> entry: params. entrySet ()){

 

StringBody par = new StringBody (entry. getValue ());

MpEntity. addPart (entry. getKey (), par );

}

}

// Image

If (! Imagepath. equals ("")){

FileBody file = new FileBody (new File (imagepath ));

MpEntity. addPart ("photo", file );

}

// Use the HttpPost object to set the URL path to be sent

HttpPost post = new HttpPost (path );

// Send the request body

Post. setEntity (mpEntity );

// Create a browser object to send the POST object to the server and return the Response Message.

DefaultHttpClient dhc = new DefaultHttpClient ();

HttpResponse response = dhc.exe cute (post );

 

 

The FileBody class can encapsulate files in a form to upload attachments.

Author: ankecheng

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.