Okhttp3  post上传文件的时候携带文件的参数的问题
   - Okhttp3  post上传文件的时候携带文件的参数怎么做啊   下面是接口文档和练习的demo求教!谢谢
	
	public class OkhttpActivity extends AppCompatActivity implements View.OnClickListener {
    private Button buttonget, button_post, button_getparams, button_posttparams, button_postfile;
    private TextView text;
    private static final String TAG = "OriginNetWorkActivity";
    private static final String URL = "http://api.nongfucang.cn/home/apitest/member_upload_img";
    private static final String Token = "4tFZb5UUk5N8GLCYU3aeselQLFRNQEOlyUL9p6uaBHIHTL6dfG";
    private RxPermissions rxPermissions;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_okhttp);
        init();
    }
    public void init() {
        buttonget = findViewById(R.id.button);
        button_post = findViewById(R.id.button_post);
        button_posttparams = findViewById(R.id.button_posttparams);
        text = findViewById(R.id.text);
        button_getparams = findViewById(R.id.button_getparams);
        button_postfile = findViewById(R.id.button_postfile);
        button_getparams.setOnClickListener(this);
        buttonget.setOnClickListener(this);
        button_post.setOnClickListener(this);
        button_posttparams.setOnClickListener(this);
        button_postfile.setOnClickListener(this);
        rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                    } else {
                        Toast.makeText(this, "有权限未通过无法开启", Toast.LENGTH_SHORT).show();
                    }
                });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                getData();
                break;
            case R.id.button_post:
                postData();
                break;
            case R.id.button_getparams:
                break;
            case R.id.button_posttparams:
                HashMap<String, String> params = new HashMap<>();
                params.put("token", Token);
                File file = new File("/storage/emulated/0/Android/data/com.nfc.shop/cache/1581842329846.jpg");
                File[] files = new File[]{file};
                String[] name = new String[]{"image"};
                postFile(URL, files, name, params);
                break;
            case R.id.button_postfile:
                break;
        }
    }
    private void postFile(String url, File[] files, String[] fileKeys, Map<String, String> params) {
        if (params == null) {
            params = new HashMap<>();
        }
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.SECONDS)
                .build();
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            /**
             * 判断值是否是空的
             */
            if (map.getValue() == null) {
                value = "";
            } else {
                value = map.getValue();
            }
            /**
             * 把key和value添加到formbody中
             */
            builder.add(key, value);
        }
        RequestBody requestBody = builder.build();
        MultipartBody.Builder multipartBody = new MultipartBody.Builder();
        multipartBody.setType(MultipartBody.ALTERNATIVE)
                .addPart(requestBody);
        if (files != null) {
            RequestBody fileBody = null;
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                String fileName = file.getName();
                fileBody = RequestBody.create(MediaType.parse("image/*"), file);
                //TODO 根据文件名设置contentType
                multipartBody.addPart(Headers.of("Content-Disposition",
                        "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
                        fileBody);
            }
            Request request = new Request.Builder()
                    .url(url)
                    .post(multipartBody.build())
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    ResponseBody body = response.body();
                    assert body != null;
                    String s = body.string();
                    setText(s);
                }
            });
        }
//        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .connectTimeout(10000, TimeUnit.SECONDS)
//                .build();
//        File file = new File("/storage/sdcard0/Pictures/1577331681917.jpg");
//        MediaType type = MediaType.parse("image/jpeg");
//        RequestBody Body = RequestBody.create(file, type);
//        RequestBody requestBody = new MultipartBody.Builder()
//                .addFormDataPart("File", file.getName(), Body)
//                .build();
//        Request request = new Request.Builder()
//                .post(requestBody)
//                .url()
//                .build();
//        Call call = okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//            }
//        });
    }
    private String guessMimeType(String fileName) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(fileName);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }
    private void postData() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(1000, TimeUnit.SECONDS)
                .build();
        Map<String, String> params = new HashMap<>();
        params.put("goodsId", "9649");
        FormBody.Builder builder = new FormBody.Builder();
//        Set<Map.Entry<String, String>> entries = params.entrySet();
//        for (Map.Entry<String, String> entry : entries) {
//            String key = entry.getKey();
//            String value;
//            if(entry.getValue()== null){
//                value = "";
//            }else{
//                value = entry.getValue();
//            }
//            builder.add(key,value);
//        }
        for (Map.Entry<String, String> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            /**
             * 判断值是否是空的
             */
            if (map.getValue() == null) {
                value = "";
            } else {
                value = map.getValue();
            }
            /**
             * 把key和value添加到formbody中
             */
            builder.add(key, value);
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .post(requestBody)
                .url("https://www.sunofbeach.net/shop/api/goods/relative")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    ResponseBody body = response.body();
                    assert body != null;
                    String s = body.string();
                    setText(s);
                }
            }
        });
    }
    private void getData() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .get()
                .url("https://www.sunofbeach.net/shop/api/discovery/categories")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    ResponseBody body = response.body();
                    assert body != null;
                    String s = body.string();
                    setText(s);
                }
            }
        });
    }
    public void setText(final String s) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                text.setText(s);
            }
        });
    }
}
Charles抓包的结果是
{
	"code": 201,
	"msg": "token 不能为空"
}
您的每一个用心回答,都会让这个世界变得更美好一些!