Android okhttp multipart boundar

2019-05-06  本文已影响0人  炫子_260f

网上okhttp multipart/form-data 请求有很多教程,这里主要是记录一些细节部分(boundary 的设置),以及最后Fiddler抓包看请求效果。

环境

okhttp:3.8.0

代码

  1. 使用默认boundary,Guid格式
    private String getUrl(String url, String filename) {
        //请求获取图片地址

        try {
            MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.setType(MediaType.parse("multipart/form-data"));

            File f=new File(filename);
            if (f!=null) {
                RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), f);
                builder.addFormDataPart("file",f.getName(), fileBody);
            }

            MultipartBody requestBody = builder.build();
            //构建请求
            Request request = new Request.Builder()
                    .url(url)//地址
                    .post(requestBody)//添加请求体
                    .build();

            response = client.newCall(request).execute();

            if (response.isSuccessful()){
                String res = "http://" + publicUrl + "/" + assignedInfo.getFid();
                Logger.d(TAG, "res ="+res);
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }
image.png image.png
  1. 自定义boundary
    MultipartBody.Builder builder = new MultipartBody.Builder(BOUNDARY);
    private String getUrl(String url, String filename) {
        //请求获取图片地址

        try {
            String BOUNDARY = "---------------------------" + new java.text.SimpleDateFormat("SSSssmmHHddMMyyyy").format(new Date());
            MultipartBody.Builder builder = new MultipartBody.Builder(BOUNDARY);
            builder.setType(MediaType.parse("multipart/form-data"));

            File f=new File(filename);
            if (f!=null) {
                RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), f);
                builder.addFormDataPart("file",f.getName(), fileBody);
            }

            MultipartBody requestBody = builder.build();
            //构建请求
            Request request = new Request.Builder()
                    .url(url)//地址
                    .post(requestBody)//添加请求体
                    .build();

            response = client.newCall(request).execute();

            if (response.isSuccessful()){
                String res = "http://" + publicUrl + "/" + assignedInfo.getFid();
                Logger.d(TAG, "res ="+res);
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

Fiddler 抓包效果


image.png image.png

原理

image.png
上一篇下一篇

猜你喜欢

热点阅读