Java使用HttpClient詳細示例_第1頁
Java使用HttpClient詳細示例_第2頁
Java使用HttpClient詳細示例_第3頁
Java使用HttpClient詳細示例_第4頁
Java使用HttpClient詳細示例_第5頁
已閱讀5頁,還剩24頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領

文檔簡介

第Java使用HttpClient詳細示例目錄準備環(huán)節(jié)第一步:在pom.xml中引入HttpClient的依賴第二步:引入fastjson依賴詳細使用示例GET無參:GET有參(方式一:直接拼接URL):GET有參(方式二:使用URI獲得HttpGet):POST無參:POST有參(普通參數(shù)):POST有參(對象參數(shù)):POST有參(普通參數(shù)+對象參數(shù)):對評論區(qū)關注度較高的問題進行相關補充:解決響應亂碼問題(示例):進行HTTPS請求并進行(或不進行)證書校驗(示例):相關方法詳情(非完美封裝):application/x-www-form-urlencoded表單請求(示例):發(fā)送文件(示例):發(fā)送流(示例):HTTP協(xié)議可能是現(xiàn)在Internet上使用得最多、最重要的協(xié)議了,越來越多的Java應用程序需要直接通過HTTP協(xié)議來訪問網(wǎng)絡資源。雖然在JDK的javanet包中已經(jīng)提供了訪問HTTP協(xié)議的基本功能,但是對于大部分應用程序來說,JDK庫本身提供的功能還不夠豐富和靈活。HttpClient是ApacheJakartaCommon下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協(xié)議的客戶端編程工具包,并且它支持HTTP協(xié)議最新的版本和建議。

HTTP和瀏覽器有點像,但卻不是瀏覽器。很多人覺得既然HttpClient是一個HTTP客戶端編程工具,很多人把他當做瀏覽器來理解,但是其實HttpClient不是瀏覽器,它是一個HTTP通信庫,因此它只提供一個通用瀏覽器應用程序所期望的功能子集,最根本的區(qū)別是HttpClient中沒有用戶界面,瀏覽器需要一個渲染引擎來顯示頁面,并解釋用戶輸入,例如鼠標點擊顯示頁面上的某處,有一個布局引擎,計算如何顯示HTML頁面,包括級聯(lián)樣式表和圖像。javascript解釋器運行嵌入HTML頁面或從HTML頁面引用的javascript代碼。來自用戶界面的事件被傳遞到javascript解釋器進行處理。除此之外,還有用于插件的接口,可以處理Applet,嵌入式媒體對象(如pdf文件,Quicktime電影和Flash動畫)或ActiveX控件(可以執(zhí)行任何操作)。HttpClient只能以編程的方式通過其API用于傳輸和接受HTTP消息。

HttpClient的主要功能:

實現(xiàn)了所有HTTP的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS等)

支持HTTPS協(xié)議

支持代理服務器(Nginx等)等

支持自動(跳轉(zhuǎn))轉(zhuǎn)向

進入正題

環(huán)境說明:JDK1.8、SpringBoot

準備環(huán)節(jié)

第一步:在pom.xml中引入HttpClient的依賴

第二步:引入fastjson依賴

注:本人引入此依賴的目的是,在后續(xù)示例中,會用到“將對象轉(zhuǎn)化為json字符串的功能”,也可以引其他有此功能的依賴。

注:SpringBoot的基本依賴配置,這里就不再多說了。

詳細使用示例

聲明:此示例中,以JAVA發(fā)送HttpClient(在test里面單元測試發(fā)送的);也是以JAVA接收的(在controller里面接收的)。

聲明:下面的代碼,本人親測有效。

GET無參:

HttpClient發(fā)送示例:

*GET---無參測試

*@date2025年7月13日下午4:18:50

@Test

publicvoiddoGetTestOne(){

//獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)

CloseableHttpClienthttpClient=HttpClientBuilder.create().build();

//創(chuàng)建Get請求

HttpGethttpGet=newHttpGet("http://localhost:12345/doGetControllerOne");

//響應模型

CloseableHttpResponseresponse=null;

try{

//由客戶端執(zhí)行(發(fā)送)Get請求

response=httpClient.execute(httpGet);

//從響應模型中獲取響應實體

HttpEntityresponseEntity=response.getEntity();

System.out.println("響應狀態(tài)為:"+response.getStatusLine());

if(responseEntity!=null){

System.out.println("響應內(nèi)容長度為:"+responseEntity.getContentLength());

System.out.println("響應內(nèi)容為:"+EntityUtils.toString(responseEntity));

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(ParseExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//釋放資源

if(httpClient!=null){

httpClient.close();

if(response!=null){

response.close();

}catch(IOExceptione){

e.printStackTrace();

}

對應接收示例:

GET有參(方式一:直接拼接URL):

HttpClient發(fā)送示例:

*GET---有參測試(方式一:手動在url后面加上參數(shù))

*@date2025年7月13日下午4:19:23

@Test

publicvoiddoGetTestWayOne(){

//獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)

CloseableHttpClienthttpClient=HttpClientBuilder.create().build();

//參數(shù)

StringBufferparams=newStringBuffer();

try{

//字符數(shù)據(jù)最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“”,不encoding的話,傳不過去)

params.append("name="+URLEncoder.encode("","utf-8"));

params.append("

params.append("age=24");

}catch(UnsupportedEncodingExceptione1){

e1.printStackTrace();

//創(chuàng)建Get請求

HttpGethttpGet=newHttpGet("http://localhost:12345/doGetControllerTwo"+""+params);

//響應模型

CloseableHttpResponseresponse=null;

try{

//配置信息

RequestConfigrequestConfig=RequestConfig.custom()

//設置連接超時時間(單位毫秒)

.setConnectTimeout(5000)

//設置請求超時時間(單位毫秒)

.setConnectionRequestTimeout(5000)

//socket讀寫超時時間(單位毫秒)

.setSocketTimeout(5000)

//設置是否允許重定向(默認為true)

.setRedirectsEnabled(true).build();

//將上面的配置信息運用到這個Get請求里

httpGet.setConfig(requestConfig);

//由客戶端執(zhí)行(發(fā)送)Get請求

response=httpClient.execute(httpGet);

//從響應模型中獲取響應實體

HttpEntityresponseEntity=response.getEntity();

System.out.println("響應狀態(tài)為:"+response.getStatusLine());

if(responseEntity!=null){

System.out.println("響應內(nèi)容長度為:"+responseEntity.getContentLength());

System.out.println("響應內(nèi)容為:"+EntityUtils.toString(responseEntity));

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(ParseExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//釋放資源

if(httpClient!=null){

httpClient.close();

if(response!=null){

response.close();

}catch(IOExceptione){

e.printStackTrace();

}

對應接收示例:

GET有參(方式二:使用URI獲得HttpGet):

HttpClient發(fā)送示例:

*GET---有參測試(方式二:將參數(shù)放入鍵值對類中,再放入URI中,從而通過URI得到HttpGet實例)

*@date2025年7月13日下午4:19:23

@Test

publicvoiddoGetTestWayTwo(){

//獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)

CloseableHttpClienthttpClient=HttpClientBuilder.create().build();

//參數(shù)

URIuri=null;

try{

//將參數(shù)放入鍵值對類NameValuePair中,再放入集合中

ListNameValuePairparams=newArrayList();

params.add(newBasicNameValuePair("name",""));

params.add(newBasicNameValuePair("age","18"));

//設置uri信息,并將參數(shù)集合放入uri;

//注:這里也支持一個鍵值對一個鍵值對地往里面放setParameter(Stringkey,Stringvalue)

uri=newURIBuilder().setScheme("http").setHost("localhost")

.setPort(12345).setPath("/doGetControllerTwo")

.setParameters(params).build();

}catch(URISyntaxExceptione1){

e1.printStackTrace();

//創(chuàng)建Get請求

HttpGethttpGet=newHttpGet(uri);

//響應模型

CloseableHttpResponseresponse=null;

try{

//配置信息

RequestConfigrequestConfig=RequestConfig.custom()

//設置連接超時時間(單位毫秒)

.setConnectTimeout(5000)

//設置請求超時時間(單位毫秒)

.setConnectionRequestTimeout(5000)

//socket讀寫超時時間(單位毫秒)

.setSocketTimeout(5000)

//設置是否允許重定向(默認為true)

.setRedirectsEnabled(true).build();

//將上面的配置信息運用到這個Get請求里

httpGet.setConfig(requestConfig);

//由客戶端執(zhí)行(發(fā)送)Get請求

response=httpClient.execute(httpGet);

//從響應模型中獲取響應實體

HttpEntityresponseEntity=response.getEntity();

System.out.println("響應狀態(tài)為:"+response.getStatusLine());

if(responseEntity!=null){

System.out.println("響應內(nèi)容長度為:"+responseEntity.getContentLength());

System.out.println("響應內(nèi)容為:"+EntityUtils.toString(responseEntity));

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(ParseExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//釋放資源

if(httpClient!=null){

httpClient.close();

if(response!=null){

response.close();

}catch(IOExceptione){

e.printStackTrace();

}

對應接收示例:

POST無參:

HttpClient發(fā)送示例:

*POST---無參測試

*@date2025年7月13日下午4:18:50

@Test

publicvoiddoPostTestOne(){

//獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)

CloseableHttpClienthttpClient=HttpClientBuilder.create().build();

//創(chuàng)建Post請求

HttpPosthttpPost=newHttpPost("http://localhost:12345/doPostControllerOne");

//響應模型

CloseableHttpResponseresponse=null;

try{

//由客戶端執(zhí)行(發(fā)送)Post請求

response=httpClient.execute(httpPost);

//從響應模型中獲取響應實體

HttpEntityresponseEntity=response.getEntity();

System.out.println("響應狀態(tài)為:"+response.getStatusLine());

if(responseEntity!=null){

System.out.println("響應內(nèi)容長度為:"+responseEntity.getContentLength());

System.out.println("響應內(nèi)容為:"+EntityUtils.toString(responseEntity));

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(ParseExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//釋放資源

if(httpClient!=null){

httpClient.close();

if(response!=null){

response.close();

}catch(IOExceptione){

e.printStackTrace();

}

對應接收示例:

POST有參(普通參數(shù)):

注:POST傳遞普通參數(shù)時,方式與GET一樣即可,這里以直接在url后綴上參數(shù)的方式示例。

HttpClient發(fā)送示例:

*POST---有參測試(普通參數(shù))

*@date2025年7月13日下午4:18:50

@Test

publicvoiddoPostTestFour(){

//獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)

CloseableHttpClienthttpClient=HttpClientBuilder.create().build();

//參數(shù)

StringBufferparams=newStringBuffer();

try{

//字符數(shù)據(jù)最好encoding以下;這樣一來,某些特殊字符才能傳過去(如:某人的名字就是“”,不encoding的話,傳不過去)

params.append("name="+URLEncoder.encode("","utf-8"));

params.append("

params.append("age=24");

}catch(UnsupportedEncodingExceptione1){

e1.printStackTrace();

//創(chuàng)建Post請求

HttpPosthttpPost=newHttpPost("http://localhost:12345/doPostControllerFour"+""+params);

//設置ContentType(注:如果只是傳普通參數(shù)的話,ContentType不一定非要用application/json)

httpPost.setHeader("Content-Type","application/json;charset=utf8");

//響應模型

CloseableHttpResponseresponse=null;

try{

//由客戶端執(zhí)行(發(fā)送)Post請求

response=httpClient.execute(httpPost);

//從響應模型中獲取響應實體

HttpEntityresponseEntity=response.getEntity();

System.out.println("響應狀態(tài)為:"+response.getStatusLine());

if(responseEntity!=null){

System.out.println("響應內(nèi)容長度為:"+responseEntity.getContentLength());

System.out.println("響應內(nèi)容為:"+EntityUtils.toString(responseEntity));

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(ParseExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//釋放資源

if(httpClient!=null){

httpClient.close();

if(response!=null){

response.close();

}catch(IOExceptione){

e.printStackTrace();

}

對應接收示例:

POST有參(對象參數(shù)):

先給出User類

HttpClient發(fā)送示例:

*POST---有參測試(對象參數(shù))

*@date2025年7月13日下午4:18:50

@Test

publicvoiddoPostTestTwo(){

//獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)

CloseableHttpClienthttpClient=HttpClientBuilder.create().build();

//創(chuàng)建Post請求

HttpPosthttpPost=newHttpPost("http://localhost:12345/doPostControllerTwo");

Useruser=newUser();

user.setName("潘曉婷");

user.setAge(18);

user.setGender("女");

user.setMotto("姿勢要優(yōu)雅~");

//我這里利用阿里的fastjson,將Object轉(zhuǎn)換為json字符串;

//(需要導入com.alibaba.fastjson.JSON包)

StringjsonString=JSON.toJSONString(user);

StringEntityentity=newStringEntity(jsonString,"UTF-8");

//post請求是將參數(shù)放在請求體里面?zhèn)鬟^去的;這里將entity放入post請求體中

httpPost.setEntity(entity);

httpPost.setHeader("Content-Type","application/json;charset=utf8");

//響應模型

CloseableHttpResponseresponse=null;

try{

//由客戶端執(zhí)行(發(fā)送)Post請求

response=httpClient.execute(httpPost);

//從響應模型中獲取響應實體

HttpEntityresponseEntity=response.getEntity();

System.out.println("響應狀態(tài)為:"+response.getStatusLine());

if(responseEntity!=null){

System.out.println("響應內(nèi)容長度為:"+responseEntity.getContentLength());

System.out.println("響應內(nèi)容為:"+EntityUtils.toString(responseEntity));

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(ParseExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//釋放資源

if(httpClient!=null){

httpClient.close();

if(response!=null){

response.close();

}catch(IOExceptione){

e.printStackTrace();

}

對應接收示例:

POST有參(普通參數(shù)+對象參數(shù)):

注:POST傳遞普通參數(shù)時,方式與GET一樣即可,這里以通過URI獲得HttpPost的方式為例。

先給出User類:

HttpClient發(fā)送示例:

*POST---有參測試(普通參數(shù)+對象參數(shù))

*@date2025年7月13日下午4:18:50

@Test

publicvoiddoPostTestThree(){

//獲得Http客戶端(可以理解為:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不一樣的)

CloseableHttpClienthttpClient=HttpClientBuilder.create().build();

//創(chuàng)建Post請求

//參數(shù)

URIuri=null;

try{

//將參數(shù)放入鍵值對類NameValuePair中,再放入集合中

ListNameValuePairparams=newArrayList();

params.add(newBasicNameValuePair("flag","4"));

params.add(newBasicNameValuePair("meaning","這是什么鬼?"));

//設置uri信息,并將參數(shù)集合放入uri;

//注:這里也支持一個鍵值對一個鍵值對地往里面放setParameter(Stringkey,Stringvalue)

uri=newURIBuilder().setScheme("http").setHost("localhost").setPort(12345)

.setPath("/doPostControllerThree").setParameters(params).build();

}catch(URISyntaxExceptione1){

e1.printStackTrace();

HttpPosthttpPost=newHttpPost(uri);

//HttpPosthttpPost=new

//HttpPost("http://localhost:12345/doPostControllerThree1");

//創(chuàng)建user參數(shù)

Useruser=newUser();

user.setName("潘曉婷");

user.setAge(18);

user.setGender("女");

user.setMotto("姿勢要優(yōu)雅~");

//將user對象轉(zhuǎn)換為json字符串,并放入entity中

StringEntityentity=newStringEntity(JSON.toJSONString(user),"UTF-8");

//post請求是將參數(shù)放在請求體里面?zhèn)鬟^去的;這里將entity放入post請求體中

httpPost.setEntity(entity);

httpPost.setHeader("Content-Type","application/json;charset=utf8");

//響應模型

CloseableHttpResponseresponse=null;

try{

//由客戶端執(zhí)行(發(fā)送)Post請求

response=httpClient.execute(httpPost);

//從響應模型中獲取響應實體

HttpEntityresponseEntity=response.getEntity();

System.out.println("響應狀態(tài)為:"+response.getStatusLine());

if(responseEntity!=null){

System.out.println("響應內(nèi)容長度為:"+responseEntity.getContentLength());

System.out.println("響應內(nèi)容為:"+EntityUtils.toString(responseEntity));

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(ParseExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

//釋放資源

if(httpClient!=null){

httpClient.close();

if(response!=null){

response.close();

}catch(IOExceptione){

e.printStackTrace();

}

對應接收示例:

對評論區(qū)關注度較高的問題進行相關補充:

提示:如果想要知道完整的具體的代碼及測試細節(jié),可去下面給的項目代碼托管鏈接,將項目clone下來進行觀察。如果需要運行測試,可以先啟動該SpringBoot項目,然后再運行相關test方法,進行測試。

解決響應亂碼問題(示例):

進行HTTPS請求并進行(或不進行)證書校驗(示例):

使用示例:

相關方法詳情(非完美封裝):

*根據(jù)是否是https請求,獲取HttpClient客戶端

*TODO本人這里沒有進行完美封裝。對于校不校驗校驗證書的選擇,本人這里是寫死

*在代碼里面的,你們在使用時,可以靈活二次封裝。

*提示:此工具類的封裝、相關客戶端、服務端證書的生成,可參考我的這篇博客:

*linked/justry_deng/article/details/91569132/linked

*@paramisHttps是否是HTTPS請求

*@returnHttpClient實例

*@date2025/9/1817:57

privateCloseableHttpClientgetHttpClient(booleanisHttps){

CloseableHttpClienthttpClient;

if(isHttps){

SSLConnectionSocketFactorysslSocketFactory;

try{

///如果不作證書校驗的話

sslSocketFactory=getSocketFactory(false,null,null);

///如果需要證書檢驗的話

//證書

//InputStreamca=this.getClass().getClassLoader().getResourceAsStream("client/ds.crt");

//證書的別名,即:key。注:cAalias只需要保證唯一即可,不過推薦使用生成keystore時使用的別名。

//StringcAalias=System.currentTimeMillis()+""+newSecureRandom().nextInt(1000);

//sslSocketFactory=getSocketFactory(true,ca,cAalias);

}catch(Exceptione){

thrownewRuntimeException(e);

httpClient=HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build();

returnhttpClient;

httpClient=HttpClientBuilder.create().build();

returnhttpClient;

*HTTPS輔助方法,為HTTPS請求創(chuàng)建SSLSocketFactory實例、TrustManager實例

*@paramneedVerifyCa

*是否需要檢驗CA證書(即:是否需要檢驗服務器的身份)

*@paramcaInputStream

*CA證書。(若不需要檢驗證書,那么此處傳null即可)

*@paramcAalias

*別名。(若不需要檢驗證書,那么此處傳null即可)

*注意:別名應該是唯一的,別名不要和其他的別名一樣,否者會覆蓋之前的相同別名的證書信息。別名即key-value中的key。

*@returnSSLConnectionSocketFactory實例

*@throwsNoSuchAlgorithmException

*異常信息

*@throwsCertificateException

*異常信息

*@throwsKeyStoreException

*異常信息

*@throwsIOException

*異常信息

*@throwsKeyManagementException

*異常信息

*@date2025/6/1119:52

privatestaticSSLConnectionSocketFactorygetSocketFactory(booleanneedVerifyCa,InputStreamcaInputStream,StringcAalias)

throwsCertificateException,NoSuchAlgorithmException,KeyStoreException,

IOException,KeyManagementException{

X509TrustManagerx509TrustManager;

//https請求,需要校驗證書

if(needVerifyCa){

KeyStorekeyStore=getKeyStore(caInputStream,cAalias);

TrustManagerFactorytrustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

trustManagerFactory.init(keyStore);

TrustManager[]trustManagers=trustManagerFactory.getTrustManagers();

if(trustManagers.length!=1||!(trustManagers[0]instanceofX509TrustManager)){

thrownewIllegalStateException("Unexpecteddefaulttrustmanagers:"+Arrays.toString(trustManagers));

x509TrustManager=(X509TrustManager)trustManagers[0];

//這里傳TLS或SSL其實都可以的

SSLContextsslContext=SSLContext.getInstance("TLS");

sslContext.init(null,newTrustManager[]{x509TrustManager},newSecureRandom());

returnnewSSLConnectionSocketFactory(sslContext);

//https請求,不作證書校驗

x509TrustManager=newX509TrustManager(){

@Override

publicvoidcheckClientTrusted(X509Certificate[]arg0,Stringarg1){

@Override

publicvoidcheckServerTrusted(X509Certificate[]arg0,Stringarg1){

//不驗證

@Override

publicX509Certificate[]getAcceptedIssuers(){

returnnewX509Certificate[0];

SSLContextsslContext=SSLContext.getInstance("TLS");

sslContext.init(null,newTrustManager[]{x509TrustManager},newSecureRandom());

returnnewSSLConnectionSocketFactory(sslContext);

*獲取(密鑰及證書)倉庫

*注:該倉庫用于存放密鑰以及證書

*@paramcaInputStream

*CA證書(此證書應由要訪問的服務端提供)

*@paramcAalias

*別名

*注意:別名應該是唯一的,別名不要和其他的別名一樣,否者會覆蓋之前的相同別名的證書信息。別名即key-value中的key。

*@return密鑰、證書倉庫

*@throwsKeyStoreException異常信息

*@throwsCertificateException異常信息

*@throwsIOException異常信息

*@throwsNoSuchAlgorithmException異常信息

*@date2025/6/1118:48

privatestaticKeyStoregetKeyStore(InputStreamcaInputStream,StringcAalias)

throwsKeyStoreException,CertificateException,IOException,NoSuchAlgorithmException{

//證書工廠

CertificateFactorycertificateFactory=CertificateFactory.getInstance("X.509");

//秘鑰倉庫

KeyStorekeyStore=KeyStore.getInstance(KeyStore.getDefaultType());

keyStore.load(null);

keyStore.setCertificateEntry(cAalias,certificateFactory.generateCertificate(caInputStream));

returnkeyStore;

}

application/x-www-form-urlencoded表單請求(示例):

發(fā)送文件(示例):

準備工作:

如果想要靈活方便的傳輸文件的話,除了引入org.apache.httpcomponents基本的httpclient依賴外再額外引入org.apache.httpcomponents的httpmime依賴。

P.S.:即便不引入httpmime依賴,也是能傳輸文件的,不過功能不夠強大。

在pom.xml中額外引入:

如果需要靈活的傳輸文件,引入此依賴后會更加方便

dependency

groupIdorg.apache.httpcomponents/groupId

artifactIdhttpmime/artifactId

version4.5.5/version

/dependency

發(fā)送端是這樣的:

*發(fā)送文件

*multipart/form-data傳遞文件(及相關信息)

*注:如果想要靈活方便的傳輸文件的話,

*除了引入org.apache.httpcomponents基本的httpclient依賴外

*再額外引入org.apache.httpcomponents的httpmime依賴。

*追注:即便不引入httpmime依賴,也是能傳輸文件的,不過功能不夠強大。

@Test

publicvoidtest4(){

CloseableHttpClienthttpClient=HttpClientBuilder.create().build();

HttpPosthttpPost=newHttpPost("http://localhost:12345/file");

CloseableHttpResponseresponse=null;

try{

MultipartEntityBuildermultipartEntityBuilder=MultipartEntityBuilder.create();

//第一個文件

StringfilesKey="files";

Filefile1=newFile("C:\\Users\\JustryDeng\\Desktop\\back.jpg");

multipartEntityBuilder.addBinaryBody(filesKey,file1);

//第二個文件(多個文件的話,使用同一個key就行,后端用數(shù)組或集合進行接收即可)

Filefile2=newFile("C:\\Users\\JustryDeng\\Desktop\\頭像.jpg");

//防止服務端收到的文件名亂碼。我們這里可以先將文件名URLEncode,然后服務端拿到文件名時在URLDecode。就能避免亂碼問題。

//文件名其實是放在請求頭的Content-Disposition里面進行傳輸?shù)?,如其值為form-data;name="files";filename="頭像.jpg"

multipartEntityBuilder.addBinaryBody(filesKey,file2,ContentType.DEFAULT_BINARY,URLEncoder.encode(file2.getName(),"utf-8"));

//其它參數(shù)(注:自定義contentType,設置UTF-8是為了防止服務端拿到的參數(shù)出現(xiàn)亂碼)

ContentTypecontentType=ContentType.create("text/plain",Charset.forName("UTF-8"));

multipartEntityBuilder.addTextBody("name","鄧沙利文",contentType);

multipartEntityBuilder.addTextBody("age","25",contentType);

HttpEntityhttpEntity=multipartEntityBuilder.build();

httpPost.setEnt

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論