无法通过apachecamel http将文件发送到rest webservice [英] Unable to send file to rest webservice via apache camel http

查看:49
本文介绍了无法通过apachecamel http将文件发送到rest webservice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Camel 的新手,在通过 Camel http 向网络服务发送文件时遇到问题.
我有一个休息 Web 服务,它使用 Multipart 表单数据类型内容并接受输入作为表单数据的一部分.当我通过骆驼发送文件和表单参数时,它在骆驼控制台上给我以下错误:

I am new to Camel and I am facing an issue while sending files to webservice via camel http.
I have a rest web service which consumes Multipart form data type content and accepts input as part of form data. When I send file and form parameter via camel it gives me the following error at camel console:

Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
org.apache.camel.component.http.HttpOperationFailedException: HTTP operation failed invoking http://localhost:8080/JAX_RS_Application/resource/restwb/upload with statusCode: 415
    at org.apache.camel.component.http.HttpProducer.populateHttpOperationFailedException(HttpProducer.java:230)
    at org.apache.camel.component.http.HttpProducer.process(HttpProducer.java:156)
    at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
    at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:129)
    at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
    at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:448)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
    at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:435)
    at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211)
    at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175)
    at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)
    at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

我在服务器端控制台上得到的错误如下:

The error i get on the server side console is as follows:

SEVERE: MessageBodyReader not found for media type=application/octet-stream, typ
e=class org.glassfish.jersey.media.multipart.FormDataMultiPart, genericType=clas
s org.glassfish.jersey.media.multipart.FormDataMultiPart.

通过 jersey 创建的 Rest web-service 的代码片段如下:

The code snippet of the Rest web-service created via jersey is as follows:

import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/restwb") 
public class FileResource {
    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String uploadFile(@FormDataParam("username") String username,@FormDataParam("password") String password,@FormDataParam("upload") InputStream is) {
            String output ="Hi "+username+" your password is "+password;
            output=output+IOUtils.LINE_SEPARATOR +IOUtils.LINE_SEPARATOR;
            output=output+"Output :"+IOUtils.LINE_SEPARATOR+"------------------------------------------------------------------------------"+IOUtils.LINE_SEPARATOR;
            try {
                output=output+IOUtils.toString(is)+IOUtils.LINE_SEPARATOR+IOUtils.LINE_SEPARATOR;
                output=output+"==================================================================================================="+IOUtils.LINE_SEPARATOR+IOUtils.LINE_SEPARATOR;
                System.out.println("Output :"+output);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return output;
    }
}

我的 Camel 配置如下:

And my Camel config is as follows:

import org.apache.camel.*;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.spi.UnitOfWork;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.james.mime4j.message.Multipart;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * Created by Manish.Pillai on 7/16/2015.
 */
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 {
                                    exchange.getContext().getTypeConverterRegistry().addTypeConverter(HttpEntity.class,InputStream.class,new InputStreamToHttpEntityConvertor());
                                    exchange.getOut().setBody(exchange.getIn().getBody(),HttpEntity.class);
                                }
                            })
                            .to("http://localhost:8080/JAX_RS_Application/resource/restwb/upload");
                }
            });

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

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

    static class InputStreamToHttpEntityConvertor implements TypeConverter {

        public boolean allowNull() {
            return false;
        }

        public <T> T convertTo(Class<T> type, Object value) throws TypeConversionException {
            Exchange exchange=(Exchange)value;

            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("upload", new FileBody(exchange.getIn().getBody(File.class), ContentType.MULTIPART_FORM_DATA, (String) exchange.getIn().getHeader(Exchange.FILE_NAME)));
            multipartEntityBuilder.addPart("username",username);
            multipartEntityBuilder.addPart("password",password);
            return (T)multipartEntityBuilder.build();
        }

        public <T> T convertTo(Class<T> aClass, Exchange exchange, Object o) throws TypeConversionException {
            return convertTo(aClass,o);
        }

        public <T> T mandatoryConvertTo(Class<T> type, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
            return convertTo(type,value);
        }

        public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
            return convertTo(type,value);
        }

        public <T> T tryConvertTo(Class<T> type, Object value) {
            return convertTo(type,value);
        }

        public <T> T tryConvertTo(Class<T> type, Exchange exchange, Object value) {
            return convertTo(type,value);
        }
    }

}

任何线索都会有所帮助.

Any leads would be helpful.

推荐答案

好吧,您的代码中有几处可以改进.

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

首先,由于您使用的是 MultipartEntityBuilder,这意味着您使用的是 Apache 的 HttpClient 版本 4.3+,因此为了获得最佳兼容性,您应该使用 Camel 的 HTTP4 组件.

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

}

我希望这会有所帮助!

这篇关于无法通过apachecamel http将文件发送到rest webservice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆