Upload and download _android of Android HTTP implementation files

Source: Internet
Author: User

Recently done a project which involves uploading and downloading features to the file, we all know that the realization of this function has been rotten street, hence, directly from the internet to swing a bunch of code, the result, found that the code is really mixed, not write incomplete, that is, there are problems, so they have to reorganize some, they sent out, I hope more people will enjoy it.

File Upload

Through the org.apache.commons.httpclient.HttpClient to achieve file upload, the jar package can be directly from the Internet search, download.

  /** * @param mcontext context * @param targeturl File upload address * @param filePath file path/public void UploadFile (FINA L activity mcontext, String targeturl, Final String filePath) {System.out.println ("TargetUrl: + targeturl +" file

    Path: "+ FilePath);
      if (Textutils.isempty (FilePath)) {Toast.maketext (mcontext, "file does not exist", toast.length_short). Show ();
    Return
        Final Postmethod filepost = new Postmethod (targeturl) {//This is used in Chinese garbled public String Getrequestcharset () {
      return "UTF-8";

    }
    };

      Try {final HttpClient client = new HttpClient ();

      File File = new file (FilePath);

        if (file.exists () && file.isfile ()) {Long fileSize = File.length ();
          if (fileSize >= 5 * 1024 * 1024) {Toast.maketext (mcontext, "file must not be greater than 5M", Toast.length_short). Show ();
        Return

        } else {Toast.maketext (mcontext, "file does not exist", toast.length_short). Show ();
      Return
}
      Upload files and parameters part[] Parts = new Part[]{new Customfilepart (File.getname (), file), new Stringpart ("File
      Name ", File.getname ()," UTF-8 ")};

      Filepost.setrequestentity (New multipartrequestentity (Parts, Filepost.getparams ()));

          New Thread (New Runnable () {@Override public void run () {int statuscode = 0;
          try {statuscode = Client.executemethod (filepost);
          catch (IOException e) {e.printstacktrace ();

          Final int finalstatuscode = statuscode; Mcontext.runonuithread (New Runnable () {@Override public void run () {if finalstat
              Uscode = = HTTPSTATUS.SC_OK) {toast.maketext (Mcontext, "Upload succeeded", Toast.length_short). Show ();
              else {toast.maketext (Mcontext, "Upload failed", Toast.length_short). Show ();
        }
            }
          });

    }). Start (); catch (exceptioN ex) {ex.printstacktrace ();

 }
  }

HttpClient use, often encounter garbled problem, we mainly in two places to solve garbled problem:
• Replication Postmethod Getrequestcharset, specifying request encoding

 Final Postmethod filepost = new Postmethod (targeturl) {//This is used to Chinese garbled public
      String Getrequestcharset () {return
        " UTF-8 ";
      }
    };

• Custom Filepart, specifying request parameter encoding

 /**
 * Solve Chinese file name garbled * * * public
class Customfilepart extends Filepart {public
  Customfilepart (String filename, file file)
      throws FileNotFoundException {
    super (filename, file);
  }

  protected void Senddispositionheader (OutputStream out) throws IOException {
    super.senddispositionheader (out);
    String filename = GetSource (). GetFileName ();
    if (filename!= null) {
      out.write (encodingutil.getasciibytes (file_name));
      Out.write (quote_bytes);
      Out.write (encodingutil.getbytes (filename, "UTF-8"));
      Out.write (quote_bytes);}}


To add parameters using Customfilepart:

part[] parts = new Part[]{new Customfilepart (File.getname (), file),
          new Stringpart ("FileName", File.getname (), " UTF-8 ")};
Filepost.setrequestentity (New multipartrequestentity (Parts, Filepost.getparams ()));

File download

Download files via HttpURLConnection.

  /** * @param urlstr file Address * @param path file Save paths * @param filename filename * @return file's absolute path/public Str
    ing downfile (string urlstr, String path, String fileName) {InputStream inputstream = null;

    String filePath = null;
      try {FileUtils FileUtils = new FileUtils ();
        Determine if the file exists if (fileutils.isfileexist (path + fileName)) {System.out.println ("exits");
      FilePath = sdpath + path + fileName;
        else {//get IO Stream inputstream = Getinputstreamfromurl (URLSTR);
        Writes files from the input stream to the SD card file Resultfile = fileutils.write2sdfrominput (path, fileName, InputStream);
        if (resultfile!= null) {FilePath = Resultfile.getpath ();
    A catch (Exception e) {e.printstacktrace ());
      Finally {try {if (InputStream!= null) inputstream.close ();
      catch (IOException e) {e.printstacktrace ();
  } return FilePath;
}

  /**   * @param urlstr * @return/Public InputStream Getinputstreamfromurl (String urlstr) {by URL
    HttpURLConnection Urlconn;
    InputStream inputstream = null;
      try {url = new URL (urlstr);
      Urlconn = (httpurlconnection) url.openconnection ();

    InputStream = Urlconn.getinputstream ();
    catch (Exception e) {e.printstacktrace ();
  return inputstream;

 }

The file download is actually very simple, plainly, is to get inputstream through HTTP, and then through parsing InputStream and write to the file.
Read InputStream and write to SDcard.

/** * Writes data from a InputStream to SD card * @param path File Save paths * @param fileName file
                 Saved name * @param input stream * @return File/Public files Write2sdfrominput (string path, String fileName,
    InputStream input) {file file = null;
    OutputStream output = null;
      try {//Create folder Createsddir (path);

      Create file = createsdfile (path + fileName);
      Opens the output stream, prepares to write the file output = new FileOutputStream (file);
      Buffers byte[] buffer = new Byte[filesize];
      int count; while (count = input.read (buffer))!=-1) {//here, be sure to write the file in this way, otherwise there will be file write errors, data loss problems output.write (buffer, 0
      , count);
    } output.flush ();
    catch (Exception e) {e.printstacktrace ();
        Finally {try {output.close ();
      Input.close ();
      catch (IOException e) {e.printstacktrace ();
  } return file; }

InputStream write to SDcard card, there is a very important place, first look at the OutputStream write method:

I recommend using the second method of write (byte[] b, int off, int len) to avoid data loss. So write the file code as follows:

 while (count = input.read (buffer))!=-1) {
 //here, be sure to write the file in this way, otherwise there will be file write errors, data loss problems
 output.write (buffer, 0, count);
}

Source Address: Https://github.com/zuiwuyuan/Http_Uploader_Downloader

The above is my arrangement of the Android HTTP implementation file upload and download methods, I hope to help more people.

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.