Required for Android-use okhttp's PUT method to upload files

Source: Internet
Author: User

Required for Android-use okhttp's PUT method to upload files
Background

The company's file upload interface uses the PUT protocol. Previously, it used the upload class in the old project. Now the okhttp network library is used in the project, so I checked the information and shared it here.

Code Implementation
/*** @ Param mediaType MediaType * @ param uploadUrl put request address * @ param localPath local file path * @ return response result and HTTP status code * @ throws IOException */public String put (MediaType mediaType, string uploadUrl, String localPath) throws IOException {File file = new File (localPath); RequestBody body = RequestBody. create (mediaType, file); Request request = new Request. builder (). url (uploadUrl ). put (body ). build (); Response response = client.newcall(requestcmd.exe cute (); return response. code () + ":" + response. body (). string () ;}// upload jpg Image public String putImg (String uploadUrl, String localPath) throws IOException {MediaType Image = MediaType. parse ("image/jpeg; charset = UTF-8"); return put (Image, uploadUrl, localPath );}

You may also need to modify the following settings:Timeout

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

PS: the above Code is based onokhttp-2.7.2Other versions are not tested and are theoretically common.

Summary

The above is the most basic code implementation. You can also add your own various listeners.

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.