http外部接口 form-data 传参file文件和json数据

package cn.com.trueway.flfg.util;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;


public class HttpClientUtil {

    private static Logger logger = LogManager.getLogger(HttpClientUtil.class);


    public static String sendHttpPostRequest(String url,JSONObject jsonObject, MultipartFile multipartFile) throws  Exception{
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entityBuilder.setCharset(Charset.forName("utf-8"));
        /***
         * 这里需要将multiPartFile 转成File文件
         */
        InputStream inputStream = multipartFile.getInputStream();
        String path = System.getProperty("java.io.tmpdir");
        FileOutputStream bufferedWriter = new FileOutputStream(path+"/"+multipartFile.getOriginalFilename());
        byte[] arr = new byte[2048];
        while((inputStream.read(arr,0,arr.length)) != -1){
            bufferedWriter.write(arr);
        }
        File file = new File(path+"/"+multipartFile.getOriginalFilename());
        entityBuilder.addTextBody("json",JSONObject.toJSONString(jsonObject));
        entityBuilder.addPart("file",new FileBody(file,multipartFile.getOriginalFilename(),multipartFile.getContentType(),"utf-8"));
        httpPost.setEntity(entityBuilder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        String responseJson = EntityUtils.toString(httpResponse.getEntity());
        return responseJson;
    }

    public static void main(String[] args) throws Exception {
        String url = "http://localhost:8080/trueOA/flfg_flfgCjLaw.do";
        HashMap<String, Object> paramMap = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("qq","111");
        jsonObject.put("ww","222");
        paramMap.put("json", jsonObject);
        File file = new File("D:\\桌面\\haiAn\\测试文档\\test.docx");
        //创建file对象
        //获取file对象的文件输入流
        MultipartFile multipartFile = getMultipartFile(file);
        String resStr = HttpClientUtil.sendHttpPostRequest(url, jsonObject,multipartFile);

        logger.info("resStr=="+resStr);
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }
}
 

引入pom

         <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值