日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java发送文件_java 模拟http发送文件和参数

發布時間:2023/12/3 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java发送文件_java 模拟http发送文件和参数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、maven:

org.apache.httpcomponents

httpmime

4.5.3

二、工具類:

import java.io.File;

import java.util.Map;

import java.util.Map.Entry;

import org.apache.http.*;

import org.apache.http.client.HttpClient;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.conn.HttpConnectionFactory;

import org.apache.http.conn.ManagedHttpClientConnection;

import org.apache.http.conn.routing.HttpRoute;

import org.apache.http.entity.ContentType;

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.DefaultHttpResponseFactory;

import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;

import org.apache.http.impl.client.HttpClientBuilder;

import org.apache.http.impl.client.LaxRedirectStrategy;

import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;

import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;

import org.apache.http.message.BasicHeader;

import org.apache.http.message.BasicLineParser;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.CharArrayBuffer;

import org.apache.http.util.EntityUtils;

import lombok.extern.slf4j.Slf4j;

/**

* @Auther: zyx.

* @Date: 2018/11/19 20:03

*/

@Slf4j

public class HttpUtils {

public static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/" +

"537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36";

public static String httpPostForFile(String url, Map fileMap, Map params,

Map headers) {

HttpClient httpClient = buildHttpClient();

try {

HttpPost httpPost = new HttpPost(url);

httpPost.setHeaders(buildHeader(headers));

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

if (fileMap != null && fileMap.size() > 0) {

for (Entry file : fileMap.entrySet()) {

FileBody fileBody = new FileBody((File) file.getValue(), ContentType.DEFAULT_BINARY);

builder = MultipartEntityBuilder.create();

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

builder.addPart(file.getKey(), fileBody);

}

}

ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);

for (Map.Entry entry : params.entrySet()) {

if (entry.getValue() == null)

continue;

builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);

}

HttpEntity entity = builder.build();

httpPost.setEntity(entity);

HttpResponse response = httpClient.execute(httpPost);

String result = "";

Integer statusCode = response.getStatusLine().getStatusCode();

if (StrUtils.isNotEmpty(statusCode) && statusCode.intValue() == HttpStatus.SC_OK) {

result = EntityUtils.toString(response.getEntity(), "utf-8");

} else {

log.error("請求地址" + url + "錯誤狀態" + response.getStatusLine().getStatusCode());

EntityUtils.consume(entity);

}

return result;

} catch (Exception e) {

log.error(e.getMessage());

}

return "";

}

public static HttpClient buildHttpClient() {

HttpConnectionFactory httpConnectionFactory = new ManagedHttpClientConnectionFactory(

new DefaultHttpRequestWriterFactory(),

new DefaultHttpResponseParserFactory(new MyLineParser(),

new DefaultHttpResponseFactory()));

PoolingHttpClientConnectionManager pccm = new PoolingHttpClientConnectionManager(

httpConnectionFactory);

pccm.setDefaultMaxPerRoute(50);

pccm.setMaxTotal(300);

HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom()

.setConnectionRequestTimeout(15000)

.setSocketTimeout(60000)

.setConnectTimeout(40000).build())

.setRedirectStrategy(new LaxRedirectStrategy())

.setConnectionManager(pccm)

.setRetryHandler(new DefaultHttpRequestRetryHandler(1, true))

.setUserAgent(DEFAULT_USER_AGENT).build();

return httpClient;

}

public static Header[] buildHeader(Map params) {

Header[] headers = null;

if (params != null && params.size() > 0) {

headers = new BasicHeader[params.size()];

int i = 0;

for (Map.Entry entry : params.entrySet()) {

headers[i] = new BasicHeader(entry.getKey(), entry.getValue());

i++;

}

}

return headers;

}

/**

* 如果返回不規范的HTTP頭,實現兼容.

*/

private static class MyLineParser extends BasicLineParser {

@Override

public Header parseHeader(

CharArrayBuffer buffer) throws ParseException {

try {

return super.parseHeader(buffer);

} catch (ParseException ex) {

return new BasicHeader("Invalid",buffer.toString());

}

}

}

}

三、發送端參數包裝:

public static List> builderSendFile(SyncLibrary sync, File file, int index, int splitNum) {

List> list = new ArrayList<>();

Map textMap = new HashMap<>();

textMap.put("methodType", sync.getMethodType());

textMap.put("splitNum", splitNum);

textMap.put("index", index);

textMap.put("libId", sync.getLibId());

textMap.put("appkey", sync.getAppkey());

Map fileMap = new HashMap<>();

fileMap.put("fileData", file);

list.add(textMap);

list.add(fileMap);

return list;

}

四、Spring controller接收:

@ResponseBody

@RequestMapping(value = "/feature/file/receive")

public ReceiveResponse receiveDate(@RequestParam(value = "fileData", required = false) MultipartFile multipartFile,

SyncSendDto dto) {

總結

以上是生活随笔為你收集整理的java发送文件_java 模拟http发送文件和参数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。