Android Network Operations (upload and download)

Source: Internet
Author: User

Java code
Package com. maidong. utils;
 
Import java. io. BufferedReader;
Import java. io. DataOutputStream;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. InputStreamReader;
Import java. io. UnsupportedEncodingException;
Import java.net. HttpURLConnection;
Import java.net. URL;
Import java.net. URLConnection;
Import java.net. URLDecoder;
Import java.net. URLEncoder;
Import java. util. ArrayList;
Import java. util. List;
Import java. util. Map;
 
Import org. apache. http. HttpEntity;
Import org. apache. http. NameValuePair;
Import org. apache. http. client. ClientProtocolException;
Import org. apache. http. client. HttpClient;
Import org. apache. http. client. entity. UrlEncodedFormEntity;
Import org. apache. http. client. methods. HttpPost;
Import org. apache. http. impl. client. DefaultHttpClient;
Import org. apache. http. protocol. HTTP;
 
Import android. app. Activity;
Import android. content. Context;
Import android.net. ConnectivityManager;
Import android.net. NetworkInfo;
 
Public class InternetUtils {
 
Private static final String USER_AGENT = "User-Agent ";
 
Public static String httpPost (String url, List <NameValuePair> nameValuePairs) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient ();
HttpPost httpPost = new HttpPost (url );
// List <NameValuePair> nameValuePairs = new ArrayList <NameValuePair> (2 );
// Your DATA
// NameValuePairs. add (new BasicNameValuePair ("id", "12345 "));
// NameValuePairs. add (new BasicNameValuePair ("stringdata ",
// "EoeAndroid.com is Cool! "));
 
HttpPost. setHeader (USER_AGENT, "Mozilla/4.5 ");
HttpEntity httpEntity = null;
Try {
HttpPost. setEntity (new UrlEncodedFormEntity (nameValuePairs, HTTP. UTF_8 ));
HttpEntity = httpclient.exe cute (httpPost). getEntity ();
} Finally {
// HttpPost. abort ();
}
Return retrieveHttpEntity (httpEntity );
}
 
Public static InputStream download (URL url) throws IOException {
URLConnection conn = url. openConnection ();
InputStream is = conn. getInputStream ();
Return is;
}
 
Public static byte [] downloadFileData (String surl) throws IOException {
URL url = new URL (surl );
URLConnection conn = url. openConnection ();
// Obtain the length
Int length = (int) conn. getContentLength ();
InputStream is = conn. getInputStream ();
Byte [] imgData = null;
If (length! =-1 ){
ImgData = new byte [length];
Byte [] temp = new byte [1, 512];
Int readLen = 0;
Int destPos = 0;
While (readLen = is. read (temp)> 0 ){
System. arraycopy (temp, 0, imgData, destPos, readLen );
DestPos + = readLen;
}
}
Return imgData;
}
 
Public static InputStream download (String url) throws IOException {
Return download (new URL (url ));
}
 
Public static String httpPost (String url) throws ClientProtocolException, IOException {
Return httpPost (url, new ArrayList <NameValuePair> ());
}
 
Private static String retrieveHttpEntity (HttpEntity httpEntity) throws UnsupportedEncodingException, IllegalStateException,
IOException {
StringBuffer stringBuffer = new StringBuffer ();
InputStreamReader is = new InputStreamReader (httpEntity. getContent (), HTTP. UTF_8 );
BufferedReader bufferedReader = new BufferedReader (is );
String line;
While (line = bufferedReader. readLine ())! = Null ){
StringBuffer. append (line );
}
Return stringBuffer. toString ();
}
 
Public static String uploadFile (String actionUrl, String newName, InputStream fStream ){
String end = "\ r \ n ";
String twoHyphens = "--";
String boundary = java. util. UUID. randomUUID (). toString ();
DataOutputStream ds = null;
Try {
URL url = new URL (actionUrl );
HttpURLConnection con = (HttpURLConnection) url. openConnection ();
/* 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 */
Ds = new DataOutputStream (con. getOutputStream ());
Ds. writeBytes (twoHyphens + boundary + end );
Ds. writeBytes ("Content-Disposition: form-data;" + "name = \" Filedata \ "; filename = \" "+ newName +" \ "" + end );
Ds. writeBytes (end );
 
/* Obtain the FileInputStream of the file */
// FileInputStream fStream = new FileInputStream (uploadFile );
/* 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 );
}
Ds. writeBytes (end );
Ds. writeBytes (twoHyphens + boundary + twoHyphens + end );
 
Ds. flush ();
 
/* Get Response content */
InputStream is = con. getInputStream ();
Int ch;
StringBuffer B = new StringBuffer ();
While (ch = is. read ())! =-1 ){
B. append (char) ch );
}
/* Display Response in Dialog */
// ShowDialog (B. toString (). trim ());
Return B. toString (). trim ();
/* Disable DataOutputStream */
 
} Catch (Exception e ){
// ShowDialog ("" + e );
} Finally {
AppUtils. close (ds );
AppUtils. close (fStream );
}
Return null;
}
 
/**
*
* @ Param s
* @ Return null if the given string is null.
* @ Throws UnsupportedEncodingException
*/
Public static String decode (String s, String enc) throws UnsupportedEncodingException {
Return s = null? Null: URLDecoder. decode (s, enc );
}
 
Public static String encode (String s, String enc) throws UnsupportedEncodingException {
Return URLEncoder. encode (s = null? "": S), enc );
}
 
/**
*
* Determine whether the network status is available
*
* @ Return true: Network available; false: Network unavailable
*/
Public static boolean isNetworkConnected (Activity activity ){
ConnectivityManager conManager = (ConnectivityManager) activity. getSystemService (Context. CONNECTIVITY_SERVICE );
NetworkInfo networkInfo = conManager. getActiveNetworkInfo ();
If (networkInfo! = Null) {// this judgment is required, or else an error will occur.
Return networkInfo. isAvailable ();
}
Return false;
}
}

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.