标签:绝对路径 data files 多个 net dep oid comm back
HttpURLConnection同时上传图片和文件仍旧未能实现,在尝试未果之后我翻看了一下OKHttp的上传方法,下面做出总结:
参考博客:
https://blog.csdn.net/nsplnpbjy/article/details/104690131
https://blog.csdn.net/yancychas/article/details/78212701
https://blog.csdn.net/gxflh/article/details/81133337?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1
OKHttp使用思路与HttpURLConnection类似,主要是在设置多个参数方面,可以使用Request.Builder,如下列代码:
原文地址:https://www.cnblogs.com/shenchanghui/p/6407271.html
1 public void call(Subscriber<? super String> subscriber) { 2 MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder(); 3 multipartBodyBuilder.setType(MultipartBody.FORM); 4 //遍历map中所有参数到builder 5 if (params != null){ 6 for (String key : params.keySet()) { 7 multipartBodyBuilder.addFormDataPart(key, params.get(key)); 8 } 9 } 10 //遍历paths中所有图片绝对路径到builder,并约定key如“upload”作为后台接受多张图片的key 11 if (files != null){ 12 for (File file : files) { 13 multipartBodyBuilder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)); 14 } 15 }
这里使用Builder进行多个参数的封装。
基本用法参考:https://www.jianshu.com/p/da4a806e599b
1 MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8"); 2 String requestBody = "I am Jdqm."; 3 Request request = new Request.Builder() 4 .url("https://api.github.com/markdown/raw") 5 .post(RequestBody.create(mediaType, requestBody)) 6 .build(); 7 OkHttpClient okHttpClient = new OkHttpClient(); 8 okHttpClient.newCall(request).enqueue(new Callback() { 9 @Override 10 public void onFailure(Call call, IOException e) { 11 Log.d(TAG, "onFailure: " + e.getMessage()); 12 } 13 14 @Override 15 public void onResponse(Call call, Response response) throws IOException { 16 Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message()); 17 Headers headers = response.headers(); 18 for (int i = 0; i < headers.size(); i++) { 19 Log.d(TAG, headers.name(i) + ":" + headers.value(i)); 20 } 21 Log.d(TAG, "onResponse: " + response.body().string()); 22 } 23 });
注意默认是GET请求,使用POST请求需要行4的写法声明.post()
接下来就是实战阶段,看看能不能使用OKHttp实现后台功能,另外冲刺日延期到下周一,加油。
标签:绝对路径 data files 多个 net dep oid comm back
原文地址:https://www.cnblogs.com/20183711PYD/p/12754874.html