android 上傳檔案

來源:互聯網
上載者:User

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 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 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.