Java httpclient請求form-data格式并設(shè)置boundary代碼實(shí)現(xiàn)方法
在 Java 開發(fā)中,經(jīng)常會遇到需要使用 httpclient 發(fā)送 form-data 格式請求的場景。本文將詳細(xì)介紹如何正確地實(shí)現(xiàn)這一操作,包括數(shù)據(jù)格式示例、常見報錯及解決方法,以及完整的 Java 代碼實(shí)現(xiàn)。
form-data 數(shù)據(jù)請求格式樣例
我們先看下 form-data 數(shù)據(jù)的格式是長什么樣的。
例如要傳輸 form-data 的鍵值對是:
a: aaa
b: bbb
請求的boundary設(shè)置如下:
addHeader(“Content-type”, “multipart/form-data;boundary=----12345”)
實(shí)際請求格式會加上boundary
,請求示例如下
----12345 Content-Disposition: form-data; name="a" aaa ----12345 Content-Disposition: form-data; name="b" bbb
postman自動生成的 boundary 如下:
Accept-Encoding: gzip, deflate, br Connection: keep-alive Content-Type: multipart/form-data; boundary=--------------------------477613155954799910398847
報錯信息: MissingServletRequestParameterException解決方法
org.springframework.web.bind.MissingServletRequestParameterException
請求Headers中的Content-Type類型不對
addHeader(“Content-Type”, “application/json; charset=UTF-8”);
將Json
換成multipart/form-data
addHeader(“Content-type”, “multipart/form-data; charset=UTF-8; boundary=” + new UUIDGenerator().next());
報錯信息: no multipart boundary was found 解決方法
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
這個報錯是沒有設(shè)置邊界分隔符
解決方法:
headers中添加boundary
addHeader("Content-type", "multipart/form-data;boundary=" + boundary)
multipart/form-data 請求參數(shù)添加boundary
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create() .setCharset(StandardCharsets.UTF_8) // [重要]:設(shè)置 setBoundary 邊界分隔符 .setBoundary(boundary);
Java代碼實(shí)現(xiàn)
【錯誤】使用 UrlEncodedFormEntity 、BasicNameValuePair 請求失?。╡rror)
public static JSONObject test(String URL) throws IOException { RequestConfig requestConfig = RequestConfig.custom().build(); try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost post = new HttpPost(URL); List<NameValuePair> list = new ArrayList<>(); BasicNameValuePair pair1 = new BasicNameValuePair("a", "aaa"); BasicNameValuePair pair2 = new BasicNameValuePair("b", "bbb"); list.add(pair1); list.add(pair2); UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,"UTF-8"); post.setEntity(urlEncodedFormEntity); String boundary = new UUIDGenerator().next(); // 設(shè)置請求格式 multipart/form-data post.addHeader("Content-type", "multipart/form-data;boundary=" + boundary); post.addHeader("Accept", "*/*"); // UTF-8 解決中文亂碼 post.addHeader("Accept-Encoding", "UTF-8"); post.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"); // 發(fā)送 post 請求 HttpResponse response = httpClient.execute(post); ...省略代碼 }
上面的代碼使用了 UrlEncodedFormEntity
,BasicNameValuePair
去設(shè)置請求格式 multipart/form-data,雖然在 Content-type
中設(shè)置了 boundary
,請求還是報請求參數(shù)錯誤:MissingServletRequestParameterException
是因?yàn)椴]有在 multipart/form-data 的請求數(shù)據(jù)前后設(shè)置 分割邊界符
【正確】使用 MultipartEntityBuilder 構(gòu)造 boundary
要使用MultipartEntityBuilder
,先引入maven
<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>
java用httpclient(apache)完整的純文本form-data請求實(shí)現(xiàn)如下:
public enum Test { ; private static final Logger logger = LoggerFactory.getLogger(Test.class); /** * setConnectTimeout: 從客戶端到url建立連接的超時時間 */ private static final int CONNECT_TIMEOUT = 30 * 1000; /** * setSocketTimeout: 連接上一個url后,獲取response的返回等待時間 */ private static final int SOCKET_TIMEOUT = 3600 * 1000; public static JSONObject postHttpFormDataPair(String URL, JSONObject requestBodyJson, Map<String, String> headersMap, String... saveRespHeaderName) { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECT_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT) .setCookieSpec(CookieSpecs.DEFAULT) .build(); CookieStore cookieStore = new BasicCookieStore(); // 默認(rèn)是 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); try (CloseableHttpClient httpClient = createSSLClientDefaultBuilder() .setDefaultRequestConfig(requestConfig) .setDefaultCookieStore(cookieStore) .build()) { HttpPost post = new HttpPost(URL); // [重要]:生成邊界分隔符 boundary String boundary = new UUIDGenerator().next(); // [重要]:設(shè)置請求格式 multipart/form-data post.addHeader("Content-type", "multipart/form-data; charset=UTF-8; boundary=" + boundary); post.addHeader("Accept", "*/*"); post.addHeader("Accept-Encoding", "UTF-8"); post.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"); if (!CollectionUtils.isEmpty(headersMap)) { for (Map.Entry<String, String> entry : headersMap.entrySet()) { post.addHeader(entry.getKey(), entry.getValue()); } } // 構(gòu)造 formdata 請求數(shù)據(jù) MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create() .setCharset(StandardCharsets.UTF_8) // [重要]:設(shè)置 setBoundary 邊界分隔符 .setBoundary(boundary); multipartEntityBuilder.addTextBody("a", "aaa"); multipartEntityBuilder.addTextBody("b", "bbb"); HttpEntity postFormDataBody = multipartEntityBuilder.build(); // 請求參數(shù) post.setEntity(postFormDataBody); // 發(fā)送 post 請求 HttpResponse response = httpClient.execute(post); if (response == null) { throw new RuntimeException("response is null"); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return getResponseJsonObject(response, saveRespHeaderName); } else { logger.warn("response status is not 200"); return getResponseJsonObject(response, saveRespHeaderName); } } catch (Exception ex) { logger.error("error:", ex); throw new RuntimeException("系統(tǒng)異常"); } } @NotNull private static JSONObject getResponseJsonObject(HttpResponse response, String[] saveRespHeaderName) throws IOException { InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String lines; StringBuilder responseMsg = new StringBuilder(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), StandardCharsets.UTF_8); responseMsg.append(lines); } reader.close(); in.close(); JSONObject jsonObject = new JSONObject(); jsonObject.put("message", responseMsg.toString()); // save header for (String name : saveRespHeaderName) { jsonObject.put(name, response.getHeaders(name)); } return jsonObject; } /** * 繞過https證書校驗(yàn) */ public static HttpClientBuilder createSSLClientDefaultBuilder() { HttpClientBuilder httpClientBuilder = null; try { SSLContextBuilder builder = new SSLContextBuilder(); // 實(shí)現(xiàn)該接口,證書受信任的X509證書校驗(yàn)為true builder.loadTrustMaterial(null, (chain, authType) -> true); // 創(chuàng)建HttpsURLConnection對象,并設(shè)置其SSLSocketFactory對象 SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), new String[]{"TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE); // HttpsURLConnection對象就可以正常連接HTTPS了,無論其證書是否經(jīng)權(quán)威機(jī)構(gòu)的驗(yàn)證,只要實(shí)現(xiàn)了接口X509TrustManager的類MyX509TrustManager信任該證書。 httpClientBuilder = HttpClients.custom().setSSLSocketFactory(socketFactory); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("系統(tǒng)異常"); } return httpClientBuilder; } }
總結(jié)
想要代碼實(shí)現(xiàn) form-data
格式的請求要注意下面2點(diǎn):
設(shè)置 boundary
邊界分隔符
設(shè)置 Content-type
到此這篇關(guān)于Java httpclient請求form-data格式并設(shè)置boundary代碼實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)Java httpclient請求form-data格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- java?11新特性HttpClient主要組件及發(fā)送請求示例詳解
- Java通過httpclient比較重定向和請求轉(zhuǎn)發(fā)
- Java HttpClient執(zhí)行請求時配置cookie流程詳細(xì)講解
- Java HttpClient-Restful工具各種請求高度封裝提煉及總結(jié)
- java中httpclient封裝post請求和get的請求實(shí)例
- java爬蟲之使用HttpClient模擬瀏覽器發(fā)送請求方法詳解
- java發(fā)送form-data請求實(shí)現(xiàn)文件上傳的示例代碼
- Java請求調(diào)用參數(shù)格式為form-data類型的接口代碼示例
- Java后臺接收數(shù)據(jù)的三種方式(url、form-data與application/json)
相關(guān)文章
Java 添加、修改、讀取、復(fù)制、刪除Excel批注的實(shí)現(xiàn)
這篇文章主要介紹了Java 添加、修改、讀取、復(fù)制、刪除Excel批注的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02Java實(shí)現(xiàn)高并發(fā)秒殺的七種方式
本文主要介紹了Java實(shí)現(xiàn)高并發(fā)秒殺的六種方式,包括使用緩存、數(shù)據(jù)庫樂觀鎖、數(shù)據(jù)庫悲觀鎖、分布式鎖、隊(duì)列限流、令牌桶算法和限流器,具有一定的參考價值,感興趣的可以了解一下2024-03-03springboot使JUL實(shí)現(xiàn)日志管理功能
這篇文章主要介紹了springboot使JUL實(shí)現(xiàn)日志管理功能,本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09springIOC的使用流程及spring中使用類型轉(zhuǎn)換器的方式
Spring IOC是Spring框架的核心原理之一,它是一種軟件設(shè)計模式,用于管理應(yīng)用程序中的對象依賴關(guān)系,這篇文章主要介紹了springIOC的使用流程以及spring中如何使用類型轉(zhuǎn)換器,需要的朋友可以參考下2023-06-06MyBatis Plus更新對象無法設(shè)空值解決方案
這篇文章主要介紹了MyBatis Plus更新對象無法設(shè)空值解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11logback EvaluatorFilter實(shí)現(xiàn)同時記錄多個level級別的日志
這篇文章主要介紹了logback EvaluatorFilter實(shí)現(xiàn)同時記錄多個level級別的日志方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11java實(shí)現(xiàn)動態(tài)驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)動態(tài)驗(yàn)證碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-03-03Java中字符數(shù)組和字符串與StringBuilder和字符串轉(zhuǎn)換的講解
今天小編就為大家分享一篇關(guān)于Java中字符數(shù)組和字符串與StringBuilder和字符串轉(zhuǎn)換的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03SpringBoot使用MyBatis時的幾種傳參規(guī)范示例
使用Mybatis作為持久層框架時,對于數(shù)據(jù)庫的增刪改查等操作都需要參數(shù)的傳遞,本文就詳細(xì)的介紹了一下SpringBoot使用MyBatis時的幾種傳參規(guī)范示例,感興趣的可以了解一下2022-02-02