Java以form表单形式提交(文件流和json数据)

HttpClientForm

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @Author 楚璃轩
 * @Date 2022/1/3  10:27
 * @Description 以表单的形式提交
 */

public class HttpClientForm {

    private static Logger logger = LoggerFactory.getLogger(HttpClientForm.class);

    public static String accessHttpPost(String url, Map<String, JSONObject> map, File file) {
        String requestJson = "";
        //传入参数可以为file或者filePath,在此处做转换
        //File file = new File(filePath);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            HttpPost httppost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //设置浏览器兼容模式
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //设置请求的编码格式
            builder.setCharset(Consts.UTF_8);
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);

            //添加文件
            //builder.addBinaryBody("cover", cover);
            if (file != null) {
                InputStream fileInputStream = new FileInputStream(file);
                builder.addBinaryBody("filename",fileInputStream, ContentType.MULTIPART_FORM_DATA, file.getName());

            }
            
            //json
            if (map != null) {
                ContentType strContent = ContentType.create("application/json", Charset.forName("UTF-8"));
                for (Map.Entry<String, JSONObject> entry : map.entrySet()) {
                   builder.addTextBody(entry.getKey(), JSONObject.toJSONString(entry.getValue()), strContent);
                }
            }
            
            HttpEntity reqEntity = builder.build();
            httppost.setEntity(reqEntity);
            httpResponse = httpClient.execute(httppost);
            requestJson = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return requestJson;
    }
}

Impl层

//某个字段内容生成附件->模拟表单以文件流形式传递
ResourceLoader resourceLoader = new DefaultResourceLoader();

//需要在【resources】目录下创建【template】目录和【fileContent.txt】文件
InputStream inputStream = resourceLoader.getResource("template/fileContent.txt").getInputStream();

//将文件转换为临时文件进行操作
File file = File.createTempFile("fileContent", ".txt");
try {
	FileUtils.copyInputStreamToFile(inputStream, file);
} finally {
	//关闭IO
	IOUtils.closeQuietly(inputStream);
}

//将某个字段内容写入临时文件中
FileWriter writer;
try {
	writer = new FileWriter(file);
	writer.write("");//清空原文件内容
	writer.write(某个字段);
	writer.flush();
	writer.close();
} catch (IOException e) {
	e.printStackTrace();
}

//存放接口响应结果
String response = "";

JSONObject jsonObject = new JSONObject();
jsonObject.put("字段",字段值);
jsonObject.put("字段",字段值);

//数据以map形式保存
Map<String, JSONObject> map = new HashMap<>();
map.put("字段", jsonObject);		

try {
	response = HttpClientForm.accessHttpPost(url,map,file);
} catch (Exception e) {
	logger.error("请求接口失败", e);
}finally {

	//删除临时文件
	boolean result = file.delete();
	if (result) {
		logger.info("File is success delete.");
	} else {
		logger.info("File doesn't exist.");
	}
}

pom.xml

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5</version>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5</version>
</dependency>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值