解決FeignClient發(fā)送post請(qǐng)求異常的問(wèn)題
FeignClient發(fā)送post請(qǐng)求異常
這個(gè)問(wèn)題其實(shí)很基礎(chǔ)。但是卻難倒了我。記錄一下
在發(fā)送post請(qǐng)求的時(shí)候要指定消息格式
正確的寫(xiě)法是這樣
@PostMapping(value = "/test/post", consumes = "application/json") String test(@RequestBody String name);
不生效的寫(xiě)法
@PostMapping(value = "/test/post", produces= "application/json")
關(guān)于這個(gè)區(qū)別
produces:它的作用是指定返回值類(lèi)型,不但可以設(shè)置返回值類(lèi)型還可以設(shè)定返回值的字符編碼;
consumes:指定處理請(qǐng)求的提交內(nèi)容類(lèi)型(Content-Type),例如application/json, text/html;
基礎(chǔ)真的很重要啊~
FeignClient調(diào)用POST請(qǐng)求時(shí)查詢(xún)參數(shù)被丟失的情況分析與處理
本文沒(méi)有詳細(xì)介紹 FeignClient 的知識(shí)點(diǎn),網(wǎng)上有很多優(yōu)秀的文章介紹了 FeignCient 的知識(shí)點(diǎn),在這里本人就不重復(fù)了,只是專(zhuān)注在這個(gè)問(wèn)題點(diǎn)上。
查詢(xún)參數(shù)丟失場(chǎng)景
業(yè)務(wù)描述: 業(yè)務(wù)系統(tǒng)需要更新用戶(hù)系統(tǒng)中的A資源,由于只想更新A資源的一個(gè)字段信息為B,所以沒(méi)有選擇通過(guò) entity 封裝B,而是直接通過(guò)查詢(xún)參數(shù)來(lái)傳遞B信息
文字描述:使用FeignClient來(lái)進(jìn)行遠(yuǎn)程調(diào)用時(shí),如果POST請(qǐng)求中有查詢(xún)參數(shù)并且沒(méi)有請(qǐng)求實(shí)體(body為空),那么查詢(xún)參數(shù)被丟失,服務(wù)提供者獲取不到查詢(xún)參數(shù)的值。
代碼描述:B的值被丟失,服務(wù)提供者獲取不到B的值
@FeignClient(name = "a-service", configuration = FeignConfiguration.class)
public interface ACall {
@RequestMapping(method = RequestMethod.POST, value = "/api/xxx/{A}", headers = {"Content-Type=application/json"})
void updateAToB(@PathVariable("A") final String A, @RequestParam("B") final String B) throws Exception;
}
問(wèn)題分析
背景
- 使用 FeignClient 客戶(hù)端
- 使用 feign-httpclient 中的 ApacheHttpClient 來(lái)進(jìn)行實(shí)際請(qǐng)求的調(diào)用
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>8.18.0</version>
</dependency>
直入源碼
通過(guò)對(duì) FeignClient 的源碼閱讀,發(fā)現(xiàn)問(wèn)題不是出在參數(shù)解析上,而是在使用 ApacheHttpClient 進(jìn)行請(qǐng)求時(shí),其將查詢(xún)參數(shù)放進(jìn)請(qǐng)求body中了,下面看源碼具體是如何處理的
feign.httpclient.ApacheHttpClient 這是 feign-httpclient 進(jìn)行實(shí)際請(qǐng)求的方法
@Override
public Response execute(Request request, Request.Options options) throws IOException {
HttpUriRequest httpUriRequest;
try {
httpUriRequest = toHttpUriRequest(request, options);
} catch (URISyntaxException e) {
throw new IOException("URL '" + request.url() + "' couldn't be parsed into a URI", e);
}
HttpResponse httpResponse = client.execute(httpUriRequest);
return toFeignResponse(httpResponse);
}
HttpUriRequest toHttpUriRequest(Request request, Request.Options options) throws
UnsupportedEncodingException, MalformedURLException, URISyntaxException {
RequestBuilder requestBuilder = RequestBuilder.create(request.method());
//per request timeouts
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(options.connectTimeoutMillis())
.setSocketTimeout(options.readTimeoutMillis())
.build();
requestBuilder.setConfig(requestConfig);
URI uri = new URIBuilder(request.url()).build();
requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath());
//request query params
List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset().name());
for (NameValuePair queryParam: queryParams) {
requestBuilder.addParameter(queryParam);
}
//request headers
boolean hasAcceptHeader = false;
for (Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
String headerName = headerEntry.getKey();
if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
hasAcceptHeader = true;
}
if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
// The 'Content-Length' header is always set by the Apache client and it
// doesn't like us to set it as well.
continue;
}
for (String headerValue : headerEntry.getValue()) {
requestBuilder.addHeader(headerName, headerValue);
}
}
//some servers choke on the default accept string, so we'll set it to anything
if (!hasAcceptHeader) {
requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*");
}
//request body
if (request.body() != null) {
//body為空,則HttpEntity為空
HttpEntity entity = null;
if (request.charset() != null) {
ContentType contentType = getContentType(request);
String content = new String(request.body(), request.charset());
entity = new StringEntity(content, contentType);
} else {
entity = new ByteArrayEntity(request.body());
}
requestBuilder.setEntity(entity);
}
//調(diào)用org.apache.http.client.methods.RequestBuilder#build方法
return requestBuilder.build();
}
org.apache.http.client.methods.RequestBuilder 此類(lèi)是 HttpUriRequest 的Builder類(lèi),下面看build方法
public HttpUriRequest build() {
final HttpRequestBase result;
URI uriNotNull = this.uri != null ? this.uri : URI.create("/");
HttpEntity entityCopy = this.entity;
if (parameters != null && !parameters.isEmpty()) {
// 這里:如果HttpEntity為空,并且為POST請(qǐng)求或者為PUT請(qǐng)求時(shí),這個(gè)方法會(huì)將查詢(xún)參數(shù)取出來(lái)封裝成了HttpEntity
// 就是在這里查詢(xún)參數(shù)被丟棄了,準(zhǔn)確的說(shuō)是被轉(zhuǎn)換位置了
if (entityCopy == null && (HttpPost.METHOD_NAME.equalsIgnoreCase(method)
|| HttpPut.METHOD_NAME.equalsIgnoreCase(method))) {
entityCopy = new UrlEncodedFormEntity(parameters, charset != null ? charset : HTTP.DEF_CONTENT_CHARSET);
} else {
try {
uriNotNull = new URIBuilder(uriNotNull)
.setCharset(this.charset)
.addParameters(parameters)
.build();
} catch (final URISyntaxException ex) {
// should never happen
}
}
}
if (entityCopy == null) {
result = new InternalRequest(method);
} else {
final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method);
request.setEntity(entityCopy);
result = request;
}
result.setProtocolVersion(this.version);
result.setURI(uriNotNull);
if (this.headergroup != null) {
result.setHeaders(this.headergroup.getAllHeaders());
}
result.setConfig(this.config);
return result;
}
解決方案
既然已經(jīng)知道原因了,那么解決方法就有很多種了,下面就介紹常規(guī)的解決方案:
- 使用 feign-okhttp 來(lái)進(jìn)行請(qǐng)求調(diào)用,這里就不列源碼了,感興趣大家可以去看, feign-okhttp 底層沒(méi)有判斷如果body為空則把查詢(xún)參數(shù)放入body中。
- 使用 io.github.openfeign:feign-httpclient:9.5.1 依賴(lài),截取部分源碼說(shuō)明原因如下:
HttpUriRequest toHttpUriRequest(Request request, Request.Options options) throws
UnsupportedEncodingException, MalformedURLException, URISyntaxException {
RequestBuilder requestBuilder = RequestBuilder.create(request.method());
//省略部分代碼
//request body
if (request.body() != null) {
//省略部分代碼
} else {
// 此處,如果為null,則會(huì)塞入一個(gè)byte數(shù)組為0的對(duì)象
requestBuilder.setEntity(new ByteArrayEntity(new byte[0]));
}
return requestBuilder.build();
}
推薦的依賴(lài)
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>9.5.1</version>
</dependency>
或者
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>9.5.1</version>
</dependency>
總結(jié)
目前絕大部分的介紹 feign 的文章都是推薦的 com.netflix.feign:feign-httpclient:8.18.0 和 com.netflix.feign:feign-okhttp:8.18.0 ,如果不巧你使用了 com.netflix.feign:feign-httpclient:8.18.0,那么在POST請(qǐng)求時(shí)并且body為空時(shí)就會(huì)發(fā)生丟失查詢(xún)參數(shù)的問(wèn)題。
這里推薦大家使用 feign-httpclient 或者是 feign-okhttp的時(shí)候不要依賴(lài) com.netflix.feign,而應(yīng)該選擇 io.github.openfeign,因?yàn)榭雌饋?lái) Netflix 很久沒(méi)有對(duì)這兩個(gè)組件進(jìn)行維護(hù)了,而是由 OpenFeign 來(lái)進(jìn)行維護(hù)了。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)的對(duì)稱(chēng)加密算法3DES定義與用法示例
這篇文章主要介紹了Java實(shí)現(xiàn)的對(duì)稱(chēng)加密算法3DES定義與用法,結(jié)合實(shí)例形式簡(jiǎn)單分析了Java 3DES加密算法的相關(guān)定義與使用技巧,需要的朋友可以參考下2018-04-04
Spring事件監(jiān)聽(tīng)機(jī)制使用和原理示例講解
Spring事件監(jiān)聽(tīng)機(jī)制是一個(gè)很不錯(cuò)的功能,我們?cè)谶M(jìn)行業(yè)務(wù)開(kāi)發(fā)的時(shí)候可以引入,在相關(guān)的開(kāi)源框架中也是用它的身影,比如高性能網(wǎng)關(guān)ShenYu中就使用了Spring事件監(jiān)聽(tīng)機(jī)制來(lái)發(fā)布網(wǎng)關(guān)的更新數(shù)據(jù),它可以降低系統(tǒng)的耦合性,使系統(tǒng)的擴(kuò)展性更好2023-06-06
Java8的Lambda遍歷兩個(gè)List匹配數(shù)據(jù)方式
這篇文章主要介紹了Java8的Lambda遍歷兩個(gè)List匹配數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
spring boot微服務(wù)自定義starter原理詳解
這篇文章主要介紹了spring boot微服務(wù)自定義starter原理詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
IntelliJ IDEA中折疊所有Java代碼,再也不怕大段的代碼了
今天小編就為大家分享一篇關(guān)于IntelliJ IDEA中折疊所有Java代碼,再也不怕大段的代碼了,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10
VSCode新手教程之配置Java環(huán)境的詳細(xì)教程
這篇文章主要給大家介紹了關(guān)于VSCode新手教程之配置Java環(huán)境的詳細(xì)教程,工欲善其事必先利其器,想要工作順利我們先搭建好JAVA的開(kāi)發(fā)環(huán)境,需要的朋友可以參考下2023-10-10
詳解使用Spring快速創(chuàng)建web應(yīng)用的兩種方式
這篇文章主要介紹了詳解使用Spring快速創(chuàng)建web應(yīng)用的兩種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
SpringBoot實(shí)現(xiàn)Excel文件批量上傳導(dǎo)入數(shù)據(jù)庫(kù)
這篇文章主要為大家詳細(xì)介紹了SpringBoot實(shí)現(xiàn)Excel文件批量上傳導(dǎo)入數(shù)據(jù)庫(kù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11

