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());

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...