Java OkHttpClient 模拟form表单提交数据&多文件

package net.cnki.thesis.collectionFee.util;

import okhttp3.*;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author :
 * @date :Created in 2022/3/25 16:59
 * @description:
 */
public class OkHttpClientUtils {
    public static void main(String[] args) throws Exception {

 

        String url="http://localhost:9010/testReceiveFormData";
        String fileFormName="files";
        Map<String,String> params=new HashMap<>();
        List<File> fileParams = new ArrayList<>();

        params.put("requestNum","abc");
        params.put("paymentMethod","个人卡建行");



        File f1=new File("E:\\保密论文名单模板 (1).xlsx");
        fileParams.add(f1);
        File f2=new File("E:\\LW.zip");
        fileParams.add(f2);

        doPostWithDataAndFile(url,params,fileParams,fileFormName);

    }

     
    /**
     *
     * @param url 地址
     * @param params 数据
     * @param fileParams 文件
     * @param fileFormName 文件的参数名
     * @throws Exception
     */
    public static Response doPostWithDataAndFile(String url,Map<String,String> params,List<File> fileParams,String fileFormName) throws Exception{


        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");

        MultipartBody.Builder builder= new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (params!=null&&params.isEmpty()==false){
            // entrySet遍历,在键和值都需要时使用(最常用)
            for (Map.Entry<String,String> entry : params.entrySet()) {
                String key= entry.getKey();
                String value=entry.getValue();
                builder.addFormDataPart(key,value);
            }
        }

        if (fileParams!=null&&fileParams.isEmpty()==false){
            for (File f: fileParams) {
                String fileName=f.getName();
                builder.addFormDataPart( fileFormName,fileName,RequestBody.create(MediaType.parse("application/octet-stream"),f));
            }
        }
        RequestBody body=builder.build();

        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .build();
        Response response = client.newCall(request).execute();
        return response;

    }
}

 

posted @ 2022-03-25 18:25  jiafeng  阅读(1533)  评论(0编辑  收藏  举报