byte []作为休息Web服务的输入

时间:2017-10-04 05:38:40

标签: java rest web service

遇到以下问题。我似乎无法将从文件创建的byte []传递到Web服务中。当我执行我的客户端代码时,服务器日志为pdfFile byte []抛出nullpointer。请在这里协助。

服务器端:

@RequestMapping(value = "/uploadForMarkPDF", method = RequestMethod.POST, consumes = { "application/octet-stream" })
    public ResponseEntity<byte[]> pdfMark(@RequestParam(value = "pdfFile", required = false)  byte[] pdfFile) {

        try {

            log.info("inside pdf Mark");

            log.info("passed in file size:"+pdfFile.length);
.
.
.

客户方:

CloseableHttpClient httpclient = null;
        byte[] data = null;
        final String uri = "http://localhost:8080/legacyRest/uploadForMarkPDF";

        File pdfFile = new File("C:\\watermarktest\\form.pdf");

        Path fileLocation = Paths.get("C:\\watermarktest\\form.pdf");

        HttpPost post = new HttpPost(uri);
        post.addHeader("Content-Type", "application/octet-stream; boundary=\"---Content Boundary\"");
        try {
            data = Files.readAllBytes(fileLocation);
        } catch (IOException ex) {

        }

        InputStream is = new ByteArrayInputStream(data);

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

        multipartEntityBuilder.addBinaryBody("pdfFile", data, ContentType.create("application/octet-stream"),
                "pdfFile");
        multipartEntityBuilder.setBoundary("---Content Boundary");
        httpclient = HttpClientBuilder.create().build();
        HttpEntity entity = multipartEntityBuilder.build();
        post.setEntity(entity);

        try {
            HttpResponse response = httpclient.execute(post);

            System.out.println(response);

            HttpEntity responseEntity = response.getEntity();

            System.out.println(responseEntity);

            InputStream responseStream = responseEntity.getContent();

1 个答案:

答案 0 :(得分:0)

问题在于客户端和对构建器的误解。

MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); // init builder

multipartEntityBuilder.addBinaryBody("pdfFile", data, ContentType.create("application/octet-stream"),
            "pdfFile");
multipartEntityBuilder.setBoundary("---Content Boundary");
HttpEntity entity = multipartEntityBuilder.build();

这个实现与正在做的

相同
HttpEntity entity = MultipartEntityBuilder.create().build();

构建器模式设置一个字段并返回构建器。这将使您能够将构建器链接在一起。但是,如果您不链接构建器,则需要确保保留对构建器的返回对象的引用,因为它们包含您希望填充的字段。

MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder = multipartEntityBuilder.setBoundary("---Content Boundary");

然而,这将是首选方法。

HttpEntity entity = MultiPartEntityBuilder.create().set*(*).set*(*).build()