概述
最近一个项目中用到了Spring MVC 计时器 + HttpClient 发送http请求,封装post请求代码如下:
httpClient = new DefaultHttpClient();
post = new HttpPost(StaticAttributes.TASK_FILE_URL);
// 请求头信息
post.setHeader("enctype", "multipart/form-data");
post.setHeader("File-Path", DeEnCode.encode(filePath));
post.addHeader("Connection", "Keep-Alive");
// 封装请求参数和文件
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileBody);
// 设置请求
post.setEntity(reqEntity);
response = httpClient.execute(post);
其中请求头 post.setHeader("File-Path", DeEnCode.encode(filePath)); value值用到了Base64加密。然后发送请求出现了一个很头疼的错误
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at org.apache.http.impl.io.AbstractSessionOutputBuffer.flushBuffer(AbstractSessionOutputBuffer.java:147)
at org.apache.http.impl.io.AbstractSessionOutputBuffer.flush(AbstractSessionOutputBuffer.java:154)
at org.apache.http.impl.io.ContentLengthOutputStream.close(ContentLengthOutputStream.java:100)
at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:123)
at org.apache.http.impl.AbstractHttpClientConnection.sendRequestEntity(AbstractHttpClientConnection.java:271)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.sendRequestEntity(ManagedClientConnectionImpl.java:197)
at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:257)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at com.demeter.server.cloud.ServerPushTaskToCloudService.pushTaskFileToCloud(ServerPushTaskToCloudService.java:90)
at com.demeter.server.cloud.ServerPushTaskToCloudService.main(ServerPushTaskToCloudService.java:105)
通过上网查询,大致原因是,客户端和服务端链接中断,但是还在读写,所以出现这种问题
一开始以为是计时器的原因,但是后来不用计时器照样出现这个错误,所以问题肯定是出现在post请求这,没有办法,通过抓包工具看了看http报文,如下:
发现,File-Path 值多了个回车换行,然后去掉这个请求头,错误没在出现。定位到问题后,接下来一点点测试,发现问题出现的原因是,Base64加密后,会在76个字符后面默认加上/r/n,就是多出的这个/r/n,导致请求一直失败。最后在加密算法中,去掉/r/n,请求顺利完成。
最后
以上就是听话火车为你收集整理的java.net.SocketException: Connection reset by peer: socket的全部内容,希望文章能够帮你解决java.net.SocketException: Connection reset by peer: socket所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复