Spring Boot,通过POST从InputStream上传文件期间的RestTemplate异常

时间:2016-10-08 21:48:59

标签: java spring post resttemplate

我正在与我的朋友应用程序一起编写,该应用程序收集JobOffer并可以手动应用它们。

例如,我从此页面Click获取CSRF令牌,因为我需要CSRF来上传文件。

但是当我试图执行restTemplate.exchange()时,我收到错误: “引起:java.lang.ClassCastException:org.springframework.core.io.ByteArrayResource无法强制转换为java.lang.String ”

这是我的班级:

@Data
@Service
class StackOverflowComAcceptor implements JobOfferService {

    private final static String BASE_URL = "http://stackoverflow.com";
    private final ConnectionService2 connectionService2;
    private final StackOverflowComFactory stackOverflowComFactory;
    private final RestTemplate restTemplate;

    @Autowired
    private CVProvider cvProvider;



    @Override
    @SneakyThrows
    public void accept(JobOffer jobOffer) {
        //List<Connection.KeyVal> templateDataEntries = stackOverflowComFactory.create();

        ConnectionRequest connectionRequest = ConnectionRequest
                .builder()
                //url is in joboffer
                .url("http://stackoverflow.com/jobs/apply/110247")
                .method(Connection.Method.GET)
                .data(new ArrayList<Connection.KeyVal>() )
                .build();


        ConnectionResponse submit1 = connectionService2.submit(connectionRequest);
        Document document = submit1.getDocument();

        String csrf = extractCSRF(document);
        String cvurl = "http://stackoverflow.com/jobs/apply/upload-resume";
        //String cvurl = "http://stackoverflow.com/jobs/apply/upload-resume?jobId=110247&fkey=" + csrf;
        InputStream inputStream = cvProvider.asInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);

        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("fkey", csrf);
        uriVariables.put("jobId", "110247");


        HttpHeaders partHeaders = new HttpHeaders();
        partHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ByteArrayResource byteArrayResource = new ByteArrayResource(bytes, "test.pdf");

        MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
        data.add("qqfile", byteArrayResource);

        HttpEntity<MultiValueMap<String, Object>> requestEntity =
                new HttpEntity<>(data, partHeaders);

        ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
//        byteArrayHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(new MediaType[]{MediaType
//                .APPLICATION_OCTET_STREAM}));
        FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        formHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
                new MediaType[]{MediaType.APPLICATION_OCTET_STREAM}));

        //restTemplate.getMessageConverters().add(byteArrayHttpMessageConverter);
        restTemplate.getMessageConverters().add(formHttpMessageConverter);

        ResponseEntity<Object> model = restTemplate.exchange(cvurl, HttpMethod.POST, requestEntity, Object.class ,
                uriVariables);

        System.out.println(model);


    }

    private String extractCSRF(Document document) {
        String s = document.getElementsByTag("script").get(0).toString();
        Pattern p = Pattern.compile("Careers.XSRF_KEY = \\\"([a-z0-9]{32})\\\""); // Regex for the value of the key
        Matcher m = p.matcher(s);
        String csrf = null;
        while( m.find() )
        {
            csrf = m.group(1); // value only
        }
        System.out.println(csrf);
        return csrf;
    }



}

这是我的stacktrace:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testStacka' defined in file [D:\WWW\Epomis\epomis\build\classes\main\net\elenx\epomis\service\com\stackoverflow\Test.class]: Invocation of init method failed; nested exception is java.lang.ClassCastException: org.springframework.core.io.ByteArrayResource cannot be cast to java.lang.String
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
    at net.elenx.Epomis.main(Epomis.java:22) [main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_74]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_74]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_74]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_74]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: java.lang.ClassCastException: org.springframework.core.io.ByteArrayResource cannot be cast to java.lang.String
    at org.springframework.http.converter.FormHttpMessageConverter.writeForm(FormHttpMessageConverter.java:292) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:254) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:89) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:849) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:617) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:588) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:507) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at net.elenx.epomis.service.com.stackoverflow.StackOverflowComAcceptor.accept(StackOverflowComAcceptor.java:99) ~[main/:na]
    at net.elenx.epomis.service.com.stackoverflow.Test.afterPropertiesSet(Test.java:40) ~[main/:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    ... 19 common frames omitted


Process finished with exit code 1   

任何想法如何解决问题?

1 个答案:

答案 0 :(得分:2)

这显然是一些问题,你正在尝试将FileMessageResource转换为String。它不一定明确地发生。你能添加堆栈跟踪吗?

好的,所以我有一个适合你的衣服,即使是其中两个,也选择你最喜欢的衣服。

  1. 您不需要使用HttpEntity<MultiValueMap<String, Object>> 有一个构造函数允许传递任何对象,所以你可以 考虑简单地使用HttpEntity<byte[]>,记得通过 byteArrayResource.getByteArray()如果​​你决定采取这个 做法。
  2. 我看过Spring api,有一个 多部分/其他内容类型的细微差别 FormHttpMessageConverter。你可以使用MultiValueMap<String, Object> 仅适用于Multipart内容类型。否则地图正在投射到 MultiValueMap<String, String>,因此运行你的错误 应用。要摆脱它只需更改内容类型 partHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);partHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);