`

http client fluent 报错案例

 
阅读更多
@RequestMapping(value = "/upload")  
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file) {  
        String uploadResult = Request.Post("http://img.g3000.net/file/upload")
                .body(MultipartEntityBuilder.create()
                        .addBinaryBody("file", file.getInputStream(), ContentType.APPLICATION_OCTET_STREAM, "file").build())
                .execute().returnContent().asString();
    }

在测试HttpClient编写的图片上传程序时抛出以下异常::
引用

[ INFO] (RetryExec.java:94) - I/O exception (java.net.SocketException) caught when processing request to {}->http://img.g3000.net:80: Connection reset by peer: socket write error
[ERROR] (ImageService.java:55) - 上传图片异常
org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at org.apache.http.client.fluent.Request.execute(Request.java:143)
at com.g3000.model.service.ImageService.upload(ImageService.java:53)
at com.g3000.controller.FileUpload.uploadUserPhoto(FileUpload.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.g3000.filter.G3000CorsFilter.filterImpl(G3000CorsFilter.java:62)
at com.g3000.filter.G3000CorsFilter.doFilter(G3000CorsFilter.java:42)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:105)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
... 53 more
Caused by: java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at org.apache.http.impl.io.SessionOutputBufferImpl.streamWrite(SessionOutputBufferImpl.java:123)
at org.apache.http.impl.io.SessionOutputBufferImpl.flushBuffer(SessionOutputBufferImpl.java:135)
at org.apache.http.impl.io.SessionOutputBufferImpl.flush(SessionOutputBufferImpl.java:142)
at org.apache.http.impl.io.ChunkedOutputStream.flush(ChunkedOutputStream.java:194)
at org.apache.http.entity.mime.content.StringBody.writeTo(StringBody.java:182)
at org.apache.http.entity.mime.AbstractMultipartForm.doWriteTo(AbstractMultipartForm.java:150)
at org.apache.http.entity.mime.AbstractMultipartForm.writeTo(AbstractMultipartForm.java:173)
at org.apache.http.entity.mime.MultipartFormEntity.writeTo(MultipartFormEntity.java:97)
at org.apache.http.impl.execchain.RequestEntityProxy.writeTo(RequestEntityProxy.java:116)
at org.apache.http.impl.DefaultBHttpClientConnection.sendRequestEntity(DefaultBHttpClientConnection.java:155)
at org.apache.http.impl.conn.CPoolProxy.sendRequestEntity(CPoolProxy.java:149)
at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:236)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:254)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
... 55 more
[ INFO] (MemcachedClientFactoryBean.java:62) - [{QA sa=/192.168.6.19:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0}]
[ INFO] (MemcachedClientFactoryBean.java:62) - [{QA sa=/192.168.6.19:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0}]


根据异常信息"Cannot retry request with a non-repeatable request entity.  The cause lists the reason the original request failed."可以确定抛出异常的原因是程序中使用了不可重复的请求实体(non-repeatable request entity)。
于是查看官方http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.htmlHttpClient Tutorial的1.1.4.1. Repeatable entitieshttp://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e113节,内容如下:
引用

An entity can be repeatable, meaning its content can be read more than once. This is only possible with self contained entities (like ByteArrayEntity or StringEntity)


根据上面对Repeatable Entity的介绍,就可以确定问题是因为构建multipartEntity时包含除ByteArrayEntity和StringEntity以外的Entity。修改代码如下:

@RequestMapping(value = "/upload")  
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file) {  
        String uploadResult = Request.Post("http://img.g3000.net/file/upload")
                .body(MultipartEntityBuilder.create()
                        .addBinaryBody("file", file.getBytes(), ContentType.APPLICATION_OCTET_STREAM, "file")
                       .build())
                .execute().returnContent().asString();
    }


验证:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jdom2.JDOMException;

import java.io.*;

public class TestMultipartForm {
    public static void main(String[] args) throws IOException, JDOMException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://10.5.13.21/upload/");

        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("pixel_middle", new StringBody("960,600"));
        multipartEntity.addPart("pixel_small", new StringBody("192,120"));
        multipartEntity.addPart("system", new StringBody("01"));
        multipartEntity.addPart("sort", new StringBody("01"));
        multipartEntity.addPart("uploader", new StringBody("0283"));
        multipartEntity.addPart("image", new InputStreamBody(new FileInputStream(new File("D:/httpclient/images/0.jpg");), file.getName()));
        
        // 显示实体是否可重复
        System.out.println("Repeatable:" + multipartEntity.isRepeatable());
        
        httpPost.setEntity(multipartEntity);
        HttpResponse response = httpclient.execute(httpPost);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } else {
                System.out.println("Error " + statusCode + "!");
            }
        } finally {
            httpPost.releaseConnection();
        }
    }
}



编译执行上述程序,结果如下:

Repeatable:false

注释第33行代码,重新编译执行程序,结果如下:

Repeatable:true

根据上面的执行结果,可以确定InputStreamBody是造成multipartEntity为不可重复实体的元凶。

HttpClient有ByteArrayBody、FileBody、InputStreamBody和StringBody四种Body。经过笔者测试,其中只有用InputStreamBody构建multipartEntity才是non-repeatable entity。

总结:

最早使用InputStreamBody而不是FileBody,是因为业务需要前置系统将图片上传到图片服务器,并保存图片链接地址到前置系统的数据库。但是前置系统是B/S架构,图片从页面上传到前置的后台是以流的方式,故而才使用InputStreamBody。最后,使用ByteArrayBody代替InputStreamBody。
分享到:
评论

相关推荐

    Fluent中常见报错及解决办法

    以下是一些常见的 Fluent 报错及其解决办法: 1. **双击无法打开 cas 或者路径出现乱码**: - 这个问题通常是由于文件路径中包含了中文字符,而 Fluent 不支持中文路径。解决方法是将包含文件的路径全部改为英文,...

    fluent案例UDS_fluent_c_fluentuds_uds_

    标题中的"fluent案例UDS_fluent_c_fluentuds_uds_"表明这是一个关于Fluent软件使用UDS(User Defined Scheme)进行数值模拟的案例研究。Fluent是一款广泛应用于流体力学、热力学以及多物理场问题的计算流体动力学...

    FLUENT 6.3 Tutorial Guide 全套官方案例文件.rar

    FLUENT 6.3 Tutorial Guide 全套官方案例文件包括 ①FLUENT 6.3 Tutorial Guide.pdf(文件详述FLUENT仿真操作步骤) ②FLUENT 6.3 Tutorial Mesh and Solution Files(包含22个教程案例的所有网格模型文件和求解文件...

    Ansys Fluent Tutorial Guide 2022 R1官方示例(全套官方案例).zip

    包括FLUENT模块所有官方案例三维示例网格文件(31个),还包括帮助文档PDF文件Ansys_Fluent_Tutorial_Guide_2022_R1.pdf,学习FLUENT各个官方案例的仿真步骤设置过程,依照各个官方案例的网格模型(.msh文件)、帮助...

    fluent表面反应案例

    【标题】"fluent表面反应案例"涉及到的是流体动力学模拟软件Fluent中的一个重要功能——表面反应。在化学工程、环境科学、能源技术等领域,理解并模拟表面反应至关重要,因为许多过程,如燃烧、催化、腐蚀等,都依赖...

    Fluent的UDF官方案例(含代码)

    标题所涉及的知识点是Fluent软件中UDF(用户定义函数)的官方案例及其代码,描述部分提到的8个案例分别为:多孔介质、壁温变化、粘度依赖温度、用户定义标量UDS、流化床中的均匀流体化、流动均匀性的计算、沉降浓度...

    Fluent实例文件.rar

    在"Fluent实例文件.rar"中,我们可能找到多种不同场景的模拟案例,例如:空气流动、燃烧、传热等。每个实例通常包含一个或多个特定问题的完整流程,从网格划分到设置边界条件,再到运行求解器和后处理。通过研究这些...

    Ansys Fluent Tutorial Guide 2021 R2 官方示例(全套官方案例)

    ANSYS 2021R2 Fuent_Tutorial_Package.zip,包括FLUENT模块所有官方案例三维示例网格文件,还有包括帮助文档PDF文件Ansys_Fluent_Tutorial_Guide_2021_R2.pdf,学习FLUENT各个官方案例的仿真步骤设置过程,依照各个...

    ansys-fluent案例

    不做商用 点击蓝字下载压缩包资源 案例内容有些简单 但是很适合初学者了解参数和各种设置步骤 实用 流体力学在路上 加油 加油

    ANSYS Fluent Tutorial Guide 19.2 教程 官方案例 tutorial 典例

    **ANSYS Fluent 19.2 教程详解** ANSYS Fluent是一款强大的计算流体动力学(CFD)软件,广泛应用于工程领域的流体流动、热传递和化学反应模拟。在19.2版本的教程中,用户可以深入学习如何有效地使用这款软件进行...

    ansys fluent空气射流案例

    总的来说,"ansys fluent空气射流案例"涉及了多相流理论、流体力学方程、边界条件、湍流模型、相变和网格划分等多个关键知识点,这些都要求分析师具备深厚的理论基础和实践经验。通过这样的模拟,我们可以深入了解...

    fluent-hc-4.2.2.jar用于设置代理

    import org.apache.http.client.fluent.*; public class proxy { public static void main(String[] args) throws Exception { HttpHost entry = new HttpHost("43.248.99.36", 62084); String resp= Executor....

    FLUENT udf 实例.zip_FLUENT-UDF_fluent udf 实例_fluent udf实例_fluent 的

    《FLUENT UDF实例详解:掌握计算流体动力学中的自定义函数编程》 FLUENT是一款广泛应用于计算流体动力学(CFD)的软件,它提供了强大的功能来模拟各种流体流动问题。然而,面对复杂或特定的流动现象,FLUENT的标准...

    Fluent 流体分析工程案例精讲第2版

    Fluent 流体分析工程案例精讲第2版,全新的Fluent教程

    Fluent help精选算例

    本文件提及的“Fluent help精选算例”实际上是一系列Fluent教程和案例分析的集合,旨在帮助Fluent用户通过具体的示例来学习和掌握Fluent软件的使用方法。这些算例涵盖了多个CFD领域的关键知识点,例如辐射、多相流...

    FLUENT 2020R2 tutorial guide PDF及案例源文件

    FLUENT 2020R2 tutorial guide PDF及案例源文件 1.What’s In This Manual The ANSYS Fluent Tutorial Guide contains a number of tutorials that teach you how to use ANSYS Flu- ent to solve different types ...

    ANSYS FLUENT 2021R2官方帮助文档及案例文件

    Ansys_Fluent_Tutorial_Guide_2021_R2 Fluent_Beta_Features_Manual Ansys_Fluent_Theory_Guide Ansys_Fluent_in_Ansys_Workbench_Users_Guide Ansys_Fluent_Users_Guide Ansys_Fluent_UDF_Manual Ansys_Fluent_...

    fluent_turorial 噪声相关案例

    《fluent_tutorial 噪声相关案例》是针对初学者设计的一系列教程,旨在帮助他们深入理解如何使用ANSYS Fluent软件进行噪声控制和分析。ANSYS Fluent是一款强大的计算流体动力学(CFD)软件,广泛应用于各种工程领域...

    Fluent 官方UDF手册+UDF案例15.0

    Fluent UDF手册+UDF案例,版本为15.0 pdf格式。ANSYS Fluent UDF Manual+Advanced User Defined Function (UDF) Tutorials,release 15.0

    FLUENT14.0 Tutorial Guide 自带算例

    Ansys FLUENT14.0 Tutorial Guide 软件自带算例文件

Global site tag (gtag.js) - Google Analytics