注:如果移动端排版有问题,请看 简书版 (<-点击左边),希望CSDN能更好的支持移动端。
背景
公司的文件上传接口使用PUT协议,之前一直用的都是老项目中的上传类,现在项目中使用了okhttp网络库,就查了下资料,在这里分享一下。
代码实现
okhttp 2.7.X
/**
* @param mediaType MediaType
* @param uploadUrl put请求地址
* @param localPath 本地文件路径
* @return 响应的结果 和 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(request).execute();
return response.code()+ ":" + response.body().string() ;
}
//上传JPG图片
public String putImg(String uploadUrl, String localPath) throws IOException {
MediaType Image = MediaType.parse("image/jpeg; charset=utf-8");
return put(Image, uploadUrl, localPath);
}
可能还需要进行的设置:修改各种Timeout
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(15, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);
okhttp 3.X
/**
* @param mediaType MediaType
* @param uploadUrl put请求地址
* @param localPath 本地文件路径
* @return 响应的结果 和 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();
//修改各种 Timeout
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(600, TimeUnit.SECONDS)
.readTimeout(200, TimeUnit.SECONDS)
.writeTimeout(600, TimeUnit.SECONDS)
.build();
//如果不需要可以直接写成 OkHttpClient client = new OkHttpClient.Builder().build();
Response response = client
.newCall(request)
.execute();
return response.body().string() + ":" + response.code();
}
//上传JPG图片
public String putImg(String uploadUrl, String localPath) throws IOException {
MediaType imageType = MediaType.parse("image/jpeg; charset=utf-8");
return put(imageType, uploadUrl, localPath);
}
总结
以上是最基本的代码实现,你还可以加上自己的各种监听。
下面是okhttp
其他方面更加详细的介绍: