android 上传文件

来源:互联网 发布:赫苏斯 数据 编辑:程序博客网 时间:2024/06/08 19:04

向服务器上传文件在android开发中是一件在普通不过的事了。正好现在项目中有用到就做一下总结吧。

  • 1.使用HttpURLConnection,这种方法比较麻烦,需要自己模拟表单提交。
  • 2.使用httpmime库实现,这种方法是建立在HttpClient基础上的。在2.3以后使用HttpURLConnection比使用HttpClient要好。
  • 3.使用OKHttp库实现。


下边就依次给出实现:

一.使用HttpURLConnection 实现

[java] view plaincopy
  1. /** 
  2.      * 上传文件 
  3.      * 
  4.      * @param path 
  5.      * @param fileList 
  6.      */  
  7.     public static void useHttpURLConnectionUploadFile(final String path,  
  8.                                                       final ArrayList<String> fileList) {  
  9.   
  10.         new Thread(new Runnable() {  
  11.   
  12.             @Override  
  13.             public void run() {  
  14.                 try {  
  15.                     URL url = new URL(path);  
  16.                     HttpURLConnection conn = (HttpURLConnection) url  
  17.                             .openConnection();  
  18.   
  19.                     conn.setRequestMethod("POST");  
  20.                     conn.setRequestProperty("Connection""keep-alive");  
  21.                     conn.setRequestProperty("Cache-Control""max-age=0");  
  22.                     conn.setRequestProperty("Accept",  
  23.                             "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");  
  24.                     conn.setRequestProperty(  
  25.                             "user-agent",  
  26.                             "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari");  
  27.                     conn.setRequestProperty("Accept-Encoding",  
  28.                             "gzip,deflate,sdch");  
  29.                     conn.setRequestProperty("Accept-Language""zh-CN,zh;q=0.8");  
  30.                     conn.setRequestProperty("Charsert""UTF-8");  
  31.                     conn.setRequestProperty("Content-Type",  
  32.                             "multipart/form-data; boundary=" + STARTBOUNDARY);  
  33.   
  34.                     OutputStream out = new DataOutputStream(conn  
  35.                             .getOutputStream());  
  36.                     StringBuffer sb = null;  
  37.                     for (int i = 0; i < fileList.size(); i++) {  
  38.                         File file = new File(fileList.get(i));  
  39.                         sb = new StringBuffer();  
  40.                         sb.append(BOUNDARY);  
  41.                         sb.append("Content-Disposition: form-data; name=\"file"  
  42.                                 + i + "\"; filename=\"" + file.getName()  
  43.                                 + "\"\r\n");  
  44.                         sb.append("Content-Type: application/octet-stream\r\n\r\n");  
  45.                         out.write(sb.toString().getBytes());  
  46.   
  47.                         DataInputStream inputStream = new DataInputStream(  
  48.                                 new FileInputStream(new File(fileList.get(i))));  
  49.   
  50.                         int bytes = 0;  
  51.                         byte buffer[] = new byte[1024];  
  52.                         while ((bytes = inputStream.read(buffer)) != -1) {  
  53.   
  54.                             out.write(buffer, 0, bytes);  
  55.                         }  
  56.                         out.write("\r\n".getBytes());  
  57.                         inputStream.close();  
  58.                     }  
  59.   
  60.                     out.write(ENDBOUNDARY.getBytes());  
  61.                     out.flush();  
  62.                     out.close();  
  63.   
  64.                     // 定义BufferedReader输入流来读取URL的响应  
  65.                     // 此处必须得到服务器端的输入流否则上传文件不成功(当php作服务器端语言的时候是这样,其它语言未试)  
  66.                     BufferedReader reader = new BufferedReader(  
  67.                             new InputStreamReader(conn.getInputStream()));  
  68.                     String line = null;  
  69.                     while ((line = reader.readLine()) != null) {  
  70.                         System.out.println(line);  
  71.                     }  
  72.   
  73.                 } catch (MalformedURLException e) {  
  74.                     e.printStackTrace();  
  75.                 } catch (IOException e) {  
  76.                     e.printStackTrace();  
  77.                 }  
  78.   
  79.             }  
  80.         }).start();  
  81.   
  82.     }  

二 、使用httpmime实现

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * 上传文件 
  3.      * 
  4.      * @param url 
  5.      * @param files 
  6.      */  
  7.     public static void useHttpMimeUploadFile(final String url,  
  8.                                              final ArrayList<String> files) {  
  9.   
  10.         new Thread(new Runnable() {  
  11.   
  12.             @Override  
  13.             public void run() {  
  14.   
  15.                 HttpClient httpClient = new DefaultHttpClient();  
  16.                 HttpPost httpPost = new HttpPost(url);  
  17.                 MultipartEntityBuilder build = MultipartEntityBuilder.create();  
  18.   
  19.                 for (String file : files) {  
  20.   
  21.                     FileBody bin = new FileBody(new File(file));  
  22.                     StringBody comment = null;  
  23.                     try {  
  24.                         comment = new StringBody("commit");  
  25.                     } catch (UnsupportedEncodingException e) {  
  26.                         e.printStackTrace();  
  27.                     }  
  28.                     build.addPart(file, bin);  
  29.                     build.addPart("comment", comment);  
  30.   
  31.                 }  
  32.   
  33.                 HttpEntity reqEntity = build.build();  
  34.                 httpPost.setEntity(reqEntity);  
  35.   
  36.                 try {  
  37.                     HttpResponse httpResponse = httpClient.execute(httpPost);  
  38.                     if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  39.                         HttpEntity resEntity = httpResponse.getEntity();  
  40.                         System.out.println(EntityUtils.toString(resEntity));  
  41.                     } else {  
  42.                         System.out.println("connection error!!!!");  
  43.                     }  
  44.   
  45.                 } catch (ClientProtocolException e) {  
  46.   
  47.                     e.printStackTrace();  
  48.                 } catch (IOException e) {  
  49.   
  50.                     e.printStackTrace();  
  51.                 } finally {  
  52.                     httpClient.getConnectionManager().shutdown();  
  53.                 }  
  54.             }  
  55.         }).start();  
  56.   
  57.     }  

三、使用OKHttp实现

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * Copyright (C) 2014 Square, Inc. 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16. package com.hotkeyfinance.finance.network;  
  17.   
  18. import com.squareup.okhttp.MediaType;  
  19. import com.squareup.okhttp.MultipartBuilder;  
  20. import com.squareup.okhttp.OkHttpClient;  
  21. import com.squareup.okhttp.Request;  
  22. import com.squareup.okhttp.RequestBody;  
  23. import com.squareup.okhttp.Response;  
  24.   
  25. import java.io.File;  
  26. import java.io.IOException;  
  27.   
  28. public final class PostMultipart {  
  29.     /** 
  30.      * The imgur client ID for OkHttp recipes. If you're using imgur for anything 
  31.      * other than running these examples, please request your own client ID! 
  32.      * https://api.imgur.com/oauth2 
  33.      */  
  34.     private static final String IMGUR_CLIENT_ID = "9199fdef135c122";  
  35.     private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");  
  36.   
  37.     private final OkHttpClient client = new OkHttpClient();  
  38.   
  39.     public void run(String url, String filePath) throws Exception {  
  40.         // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image  
  41.   
  42.         File file = new File(filePath);  
  43.   
  44.         RequestBody requestBody = new MultipartBuilder()  
  45.                 .type(MultipartBuilder.FORM)  
  46.                 .addFormDataPart("title""Square Logo")  
  47.                 .addFormDataPart("image", file.getName(),  
  48.                         RequestBody.create(MEDIA_TYPE_PNG, file))  
  49.                 .build();  
  50.   
  51.         Request request = new Request.Builder()  
  52.                 .header("Authorization""Client-ID " + IMGUR_CLIENT_ID)  
  53.                 .url(url)  
  54.                 .post(requestBody)  
  55.                 .build();  
  56.   
  57.         Response response = client.newCall(request).execute();  
  58.         if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);  
  59.   
  60.         System.out.println(response.body().string());  
  61.     }  
  62.   
  63. }  

OKHttp库的地址:   https://github.com/square/okhttp

httpmine库的地址: http://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime

0 0
原创粉丝点击