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.2
Other 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.