Unable to send file to rest webservice via apache camel http

旧巷老猫 提交于 2019-12-01 10:58:51

Well, there are several things that can be improved in your code.

First, since you are using a MultipartEntityBuilder, that means you're using Apache's HttpClient version 4.3+, so for best compatibility you should use Camel's HTTP4 component.

Third, in an example as small as this, you don't really need to use the converter, you can do something like this:

public class LoggingMain {

    private static final Logger logger = Logger.getLogger(LoggingMain.class);

    public static void main(String[] args) throws Exception {
        CamelContext camelContext = new DefaultCamelContext();
        try {
            camelContext.addRoutes(new RouteBuilder() {
                @Override
                public void configure() throws Exception {
                    from("file:C:\\temp?delay=5000&move=processed&moveFailed=error&antExclude=**/processed/**,**/error/**")
                            .process(new Processor() {
                                public void process(Exchange exchange) throws Exception {
                                    StringBody username = new StringBody("username", ContentType.MULTIPART_FORM_DATA);
                                    StringBody password = new StringBody("password", ContentType.MULTIPART_FORM_DATA);

                                    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                                    multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                                    multipartEntityBuilder.addPart("username", username);
                                    multipartEntityBuilder.addPart("password", password);

                                    String filename = (String) exchange.getIn().getHeader(Exchange.FILE_NAME);
                                    File file = exchange.getIn().getBody(File.class);
                                    multipartEntityBuilder.addPart("upload", new FileBody(file, ContentType.MULTIPART_FORM_DATA, filename));

                                    exchange.getIn().setBody(multipartEntityBuilder.build());
                                }
                            })
                            .to("http4://localhost:8080/JAX_RS_Application/resource/restwb/upload");
                }
            });

            camelContext.getRestConfiguration();
            camelContext.start();
            Thread.sleep(5000);
            camelContext.stop();

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

}

I hope this helps!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!