android 上传文件
向服务器上传文件在android开发中是一件在普通不过的事了。正好现在项目中有用到就做一下总结吧。
- 1.使用HttpURLConnection,这种方法比较麻烦,需要自己模拟表单提交。
- 2.使用httpmime库实现,这种方法是建立在HttpClient基础上的。在2.3以后使用HttpURLConnection比使用HttpClient要好。
- 3.使用OKHttp库实现。
下边就依次给出实现:
一.使用HttpURLConnection 实现
/** * 上传文件 * * @param path * @param fileList */ public static void useHttpURLConnectionUploadFile(final String path, final ArrayList<String> fileList) { new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("Cache-Control", "max-age=0"); conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); conn.setRequestProperty( "user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari"); conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch"); conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + STARTBOUNDARY); OutputStream out = new DataOutputStream(conn .getOutputStream()); StringBuffer sb = null; for (int i = 0; i < fileList.size(); i++) { File file = new File(fileList.get(i)); sb = new StringBuffer(); sb.append(BOUNDARY); sb.append("Content-Disposition: form-data; name=\"file" + i + "\"; filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type: application/octet-stream\r\n\r\n"); out.write(sb.toString().getBytes()); DataInputStream inputStream = new DataInputStream( new FileInputStream(new File(fileList.get(i)))); int bytes = 0; byte buffer[] = new byte[1024]; while ((bytes = inputStream.read(buffer)) != -1) { out.write(buffer, 0, bytes); } out.write("\r\n".getBytes()); inputStream.close(); } out.write(ENDBOUNDARY.getBytes()); out.flush(); out.close(); // 定义BufferedReader输入流来读取URL的响应 // 此处必须得到服务器端的输入流否则上传文件不成功(当php作服务器端语言的时候是这样,其它语言未试) BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); }
二 、使用httpmime实现
/** * 上传文件 * * @param url * @param files */ public static void useHttpMimeUploadFile(final String url, final ArrayList<String> files) { new Thread(new Runnable() { @Override public void run() { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder build = MultipartEntityBuilder.create(); for (String file : files) { FileBody bin = new FileBody(new File(file)); StringBody comment = null; try { comment = new StringBody("commit"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } build.addPart(file, bin); build.addPart("comment", comment); } HttpEntity reqEntity = build.build(); httpPost.setEntity(reqEntity); try { HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = httpResponse.getEntity(); System.out.println(EntityUtils.toString(resEntity)); } else { System.out.println("connection error!!!!"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } } }).start(); }
三、使用OKHttp实现
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hotkeyfinance.finance.network; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.File; import java.io.IOException; public final class PostMultipart { /** * The imgur client ID for OkHttp recipes. If you're using imgur for anything * other than running these examples, please request your own client ID! * https://api.imgur.com/oauth2 */ private static final String IMGUR_CLIENT_ID = "9199fdef135c122"; private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); private final OkHttpClient client = new OkHttpClient(); public void run(String url, String filePath) throws Exception { // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image File file = new File(filePath); RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addFormDataPart("title", "Square Logo") .addFormDataPart("image", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)) .build(); Request request = new Request.Builder() .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID) .url(url) .post(requestBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } }
OKHttp库的地址: https://github.com/square/okhttp
httpmine库的地址: http://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。