Android okhttp multipart boundary 的设置

网上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 "";
    }
Android okhttp multipart boundary 的设置_第1张图片
image.png
Android okhttp multipart boundary 的设置_第2张图片
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 抓包效果


Android okhttp multipart boundary 的设置_第3张图片
image.png
Android okhttp multipart boundary 的设置_第4张图片
image.png

原理

Android okhttp multipart boundary 的设置_第5张图片
image.png

你可能感兴趣的:(Android okhttp multipart boundary 的设置)