Android must know-upload files using Okhttp's Put method

Source: Internet
Author: User

Background

The company's file upload interface using put protocol, has been using the old project in the upload class, now the project uses the Okhttp network library, the following information, here to share.

Code implementation
    /** * @param MediaType mediatype * @param uploadurl put request address * @param LocalPath Local file path * Results of @return response and HTTP status code * @throws IOException */     PublicStringput(mediatype mediatype, string Uploadurl, String localPath)throwsIOException {File File =NewFile (LocalPath);        Requestbody BODY = requestbody.create (mediatype, file); Request Request =NewRequest.builder (). URL (uploadurl). put (body). Build (); Response Response = client.newcall (Request). Execute ();returnResponse.code () +":"+ Response.body (). String (); }//upload JPG images     PublicStringputimg(String uploadurl, String localPath)throwsIOException {MediaType Image = Mediatype.parse ("IMAGE/JPEG; Charset=utf-8 ");returnPut (Image, Uploadurl, LocalPath); }

Settings you might want to make: modify variousTimeout

new OkHttpClient();client.setConnectTimeout(30, TimeUnit.SECONDS);client.setReadTimeout(15, TimeUnit.SECONDS);client.setWriteTimeout(30, TimeUnit.SECONDS);

PS: The above code okhttp-2.7.2 is based on, other versions are not tested, theoretically generic.

Summarize

The above is the most basic code implementation, you can also add their own various monitoring.
Here is a okhttp more detailed introduction to other aspects:

Github:okhttp
Android must know-upload files using Okhttp's Put method
Okhttp Using Tutorials

Android must know-upload files using Okhttp's Put method

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.