android用okhttp发送带header带参数的post上传文件请求

    public static Map sendPost_file(String url, Map map_header, Map map_body, String parameterName, String path_file, String fileType) throws IOException {
        //添加文件
        File file = new File(path_file);
        MultipartBody.Builder builder_file = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder_file.addFormDataPart(parameterName, file.getName(), RequestBody.create(file, MediaType.parse(fileType)));
        //添加header
        Headers.Builder builder_header = new Headers.Builder();
        for (String key : map_header.keySet()) {
            builder_header.add(key, Objects.requireNonNull(map_header.get(key)));
        }
        Headers headers = builder_header.build();
        //添加参数
        for (String key : map_body.keySet()) {
            builder_file.addFormDataPart(key, Objects.requireNonNull(map_body.get(key)));
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).headers(headers).post(builder_file.build()).build();
        LocalTime startTime = LocalTime.now();//响应开始时间
        Response response = client.newCall(request).execute();
        LocalTime endTime = LocalTime.now();//响应结束时间
        int code = response.code();
        if (code != 200) {
            Log.e(cn.uiautomator.Constants.TAG, url + "\n" + response);
        }
        Map map = new HashMap<>();
        map.put("code", code);
        map.put("entity", Objects.requireNonNull(response.body()).string());
        map.put("responseTime", Duration.between(startTime, endTime).toMillis());
        response.close();
        return map;
    }

 

你可能感兴趣的:(安卓开发)