springboot RestTemplate post 两个tcp数据包 webserver报错
创始人
2024-05-30 10:32:42
0

问题

springboot RestTemplate post请求外部接口时,报错误;

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://ip:port": 
Unexpected end of file from server; nested exception is java.net.SocketException: Unexpected end of file from server

同样的请求内容使用postman则不报错,使用wireshark抓包后发现,RestTemplate 发送的http虽然未达到tcp MSS(默认的1460字节),但仍然分为两个tcp数据包
在这里插入图片描述

而postman使用了一个tcp数据包,我们知道,应用层是无法控制tcp数据包数量的。
默认的,resttemplate使用java.net.HttpURLConnection发送请求,

The default constructor uses java.net.HttpURLConnection to perform requests. You can switch to a different HTTP library with an implementation of ClientHttpRequestFactory. There is built-in support
for the following:
Apache HttpComponents
Netty
OkHttp

从源码得知,HttpURLConnection在发送http body之前会先发送header并且调用了flush方法,

org.springframework.http.client.SimpleBufferingClientHttpRequest
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
//将http body写入到输出流FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());}	

这里的 this.connection,是jdk的内部实现sun.net.www.protocol.http.HttpURLConnection,每次调用getOutputStream()就会调用flush方法

sun.net.www.http.HttpClient
public void writeRequests(MessageHeader head,PosterOutputStream pos) throws IOException {requests = head;//将http header写入到输出流中requests.print(serverOutput);poster = pos;if (poster != null)poster.writeTo(serverOutput);//这一行很重要   serverOutput.flush();}

而将RestTemplate实现换为apache httpclient后,请求接口也是正常的,抓包后发现发送了一个tcp数据包。查源码发现,apache httpclient往流中写入header后并未flush,可能就是这个原因引起的,apache httpclient最终使用的org.apache.http.impl.conn.DefaultClientConnection发送请求。

public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException {if (log.isDebugEnabled()) {log.debug("Sending request: " + request.getRequestLine());}super.sendRequestHeader(request);if (headerLog.isDebugEnabled()) {headerLog.debug(">> " + request.getRequestLine().toString());final Header[] headers = request.getAllHeaders();for (final Header header : headers) {headerLog.debug(">> " + header.toString());}}}
org.apache.http.impl.AbstractHttpClientConnection
public void sendRequestHeader(final HttpRequest request)throws HttpException, IOException {Args.notNull(request, "HTTP request");assertOpen();this.requestWriter.write(request);this.metrics.incrementRequestCount();}
org.apache.http.impl.io.AbstractMessageWriterpublic void write(final T message) throws IOException, HttpException {Args.notNull(message, "HTTP message");//写完http header后,并未调用flushwriteHeadLine(message);for (final HeaderIterator it = message.headerIterator(); it.hasNext(); ) {final Header header = it.nextHeader();this.sessionBuffer.writeLine(lineFormatter.formatHeader(this.lineBuf, header));}this.lineBuf.clear();this.sessionBuffer.writeLine(this.lineBuf);}

回顾flush方法

翻阅API,java.io.OutputStream

/*** Flushes this output stream and forces any buffered output bytes* to be written out. The general contract of flush is* that calling it is an indication that, if any bytes previously* written have been buffered by the implementation of the output* stream, such bytes should immediately be written to their* intended destination.* 

* If the intended destination of this stream is an abstraction provided by* the underlying operating system, for example a file, then flushing the* stream guarantees only that bytes previously written to the stream are* passed to the operating system for writing; it does not guarantee that* they are actually written to a physical device such as a disk drive.*

* The flush method of OutputStream does nothing.** @exception IOException if an I/O error occurs.*/public void flush() throws IOException {}

翻译过来就是强制将输出流中缓存的字节数据写入到目的地;如果目的地是一个文件,那么只能确保缓存字节写入到操作系统不能确保实际写入到磁盘;

解决

推测对方的web server实现有问题,不支持一个post请求两个tcp数据包,最终使用apache httpclient来作为RestTemplate的实现方式。

RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

相关内容

热门资讯

Python|位运算|数组|动... 目录 1、只出现一次的数字(位运算,数组) 示例 选项代...
张岱的人物生平 张岱的人物生平张岱(414年-484年),字景山,吴郡吴县(今江苏苏州)人。南朝齐大臣。祖父张敞,东...
西游西后传演员女人物 西游西后传演员女人物西游西后传演员女人物 孙悟空 六小龄童 唐僧 徐少华 ...
名人故事中贾岛作诗内容简介 名人故事中贾岛作诗内容简介有一次,贾岛骑驴闯了官道.他正琢磨着一句诗,名叫《题李凝幽居》全诗如下:闲...
和男朋友一起优秀的文案? 和男朋友一起优秀的文案?1.希望是惟一所有的人都共同享有的好处;一无所有的人,仍拥有希望。2.生活,...
戴玉手镯的好处 戴玉手镯好还是... 戴玉手镯的好处 戴玉手镯好还是碧玺好 女人戴玉?戴玉好还是碧玺好点佩戴手镯,以和田玉手镯为佳!相嫌滑...
依然什么意思? 依然什么意思?依然(汉语词语)依然,汉语词汇。拼音:yī    rán基本解释:副词,指照往常、依旧...
高尔基的散文诗 高尔基的散文诗《海燕》、《大学》、《母亲》、《童年》这些都是比较出名的一些代表作。
心在飞扬作者简介 心在飞扬作者简介心在飞扬作者简介如下。根据相关公开资料查询,心在飞扬是一位优秀的小说作者,他的小说作...
卡什坦卡的故事赏析? 卡什坦卡的故事赏析?讲了一只小狗的故事, 我也是近来才读到这篇小说. 作家对动物的拟人描写真是惟妙...
林绍涛为简艾拿绿豆糕是哪一集 林绍涛为简艾拿绿豆糕是哪一集第三十二集。 贾宽认为是阎帅间接导致刘映霞住了院,第二天上班,他按捺不...
小爱同学是女生吗小安同学什么意... 小爱同学是女生吗小安同学什么意思 小爱同学,小安同学说你是女生。小安是男的。
内分泌失调导致脸上长斑,怎么调... 内分泌失调导致脸上长斑,怎么调理内分泌失调导致脸上长斑,怎么调理先调理内分泌,去看中医吧,另外用好的...
《魔幻仙境》刺客,骑士人物属性... 《魔幻仙境》刺客,骑士人物属性加点魔幻仙境骑士2功1体质
很喜欢她,该怎么办? 很喜欢她,该怎么办?太冷静了!! 太理智了!爱情是需要冲劲的~不要考虑着考虑那~否则缘...
言情小说作家 言情小说作家我比较喜欢匪我思存的,很虐,很悲,还有梅子黄时雨,笙离,叶萱,还有安宁的《温暖的玄》 小...
两个以名人的名字命名的风景名胜... 两个以名人的名字命名的风景名胜?快太白楼,李白。尚志公园,赵尚志。
幼儿教育的代表人物及其著作 幼儿教育的代表人物及其著作卡尔威特的《卡尔威特的教育》,小卡尔威特,他儿子成了天才后写的《小卡尔威特...
海贼王中为什么说路飞打凯多靠霸... 海贼王中为什么说路飞打凯多靠霸气升级?凯多是靠霸气升级吗?因为之前刚到时确实打不过人家因为路飞的实力...
运气不好拜财神有用吗运气不好拜... 运气不好拜财神有用吗运气不好拜财神有没有用1、运气不好拜财神有用。2、拜财神上香前先点蜡烛,照亮人神...