Android Upload file

Source: Internet
Author: User

Uploading files to the server is a common thing in Android development. Just make a summary of what is now useful in the project.

    • 1. Using HttpURLConnection, this method is cumbersome and requires you to simulate the form submission yourself.
    • 2. Using the Httpmime library implementation, this method is based on the httpclient. It is better to use httpurlconnection after 2.3 than to use httpclient.
    • 3. Implement using the Okhttp library.


The following gives the implementation in turn:

I. Implementation with HttpURLConnection

/** * Upload file * * @param path * @param fileList */public static void Usehttpurlconnectionuploadfile (f Inal String Path, final arraylist<string> fileList) {NE W 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.ge                        T (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 ();                    Define the BufferedReader input stream to read the response of the URL//the server-side input stream must be obtained or the uploaded file is unsuccessful (this is true when PHP is the server-side language, not in other languages) 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 (); }

Second, the use of httpmime implementation

/** * Upload file * * @param URL * @param files * * public static void Usehttpmimeuploadfile (Final String u            RL, 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);                    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 () = = () {httpentity resentity = Httpresponse.gete                        Ntity ();                    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 (); }

Third, the use of okhttp implementation

/* * Copyright (C) Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "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, 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 {//with 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). Addformdatapa RT ("title", "Square Logo"). Addformdatapart ("image", File.getname (), Requestbody.cre        Ate (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 ()); }}

Address of the Okhttp library: https://github.com/square/okhttp

Address of the Httpmine library: http://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime

Android Upload file

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.