java 模擬http發送文件和參數

一、maven:

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

二、工具類:

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<String, Object> fileMap, Map<String, Object> params,
                                         Map<String, String> 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<String, Object> 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<String, Object> 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<HttpRoute, ManagedHttpClientConnection> 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<String, String> params) {
        Header[] headers = null;
        if (params != null && params.size() > 0) {
            headers = new BasicHeader[params.size()];
            int i = 0;
            for (Map.Entry<String, String> 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<Map<String, Object>> builderSendFile(SyncLibrary sync, File file, int index, int splitNum) {
    List<Map<String, Object>> list = new ArrayList<>();
    Map<String, Object> 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<String, Object> 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) {
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章