400使用java客户端通过rest api上传文件时的错误请求

400使用java客户端通过rest api上传文件时的错误请求,java,rest,Java,Rest,我有一个需求,我需要编写一个restapi来允许上传一个文件,以及一个基于Java的客户端来调用带有文件信息的API 下面是到目前为止我编写的代码- @POST @Path("/uploadFile") public String handleFileUpload(@RequestParam("file") MultipartFile file) { String name = file.getOriginalFilename(); if (!fi

我有一个需求,我需要编写一个restapi来允许上传一个文件,以及一个基于Java的客户端来调用带有文件信息的API

下面是到目前为止我编写的代码-

@POST
    @Path("/uploadFile")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        String name = file.getOriginalFilename();
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(uploadLocation + name)));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + uploadLocation + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }
下面是我编写的java客户机-

public class TestFileUpload {

    public static void main(String args[]) throws Exception
    {
        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost("http://localhost:8080/upload/uploadFile");
        httppost.setHeader("content-type", "false");
        File file = new File("C:\\dummyUpload.txt");

        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file, "multipart/form-data");
        mpEntity.addPart("file", cbFile);


        httppost.setEntity(mpEntity);
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (resEntity != null) {
          System.out.println(EntityUtils.toString(resEntity));
        }
        if (resEntity != null) {
          resEntity.consumeContent();
        }

        httpclient.getConnectionManager().shutdown();
    }
}
然而,当我启动服务器时,我可以看到API正在运行,当我运行客户端代码时,我收到了400个错误的请求

任何线索,可能是什么问题

比尔


AJ

您通常会像这样构建一个文件上载请求(复制自):


“内容类型”标题值“false”无效。它应该反映数据的内容类型

例如,如果您的内容主体是JSON,则内容类型标题应设置为“application/JSON”,XML应设置为“application/XML”等。。如果内容是纯文本,只需设置“text/plain


您可以阅读可用的内容类型。

删除标题ContentType如果您为表单数据添加了任何内容,则无内容。

HTTP状态消息是什么?需要内容长度标题?不确定这是否是您要求的,下面是我收到的消息-HTTP/1.1 400错误请求HTTP状态400-错误请求类型状态报告消息错误请求说明客户端发送的请求在语法上不正确。


Apache Tomcat/8.0.30i不需要任何内容长度限制,因此不是必需的。“客户端发送的请求在语法上不正确”,这是http状态消息。什么是“content type”false?根本不设置content type会出现415错误,您建议的值是什么?给定我的控制器代码,我将使用此控制器加载zip数据…任何建议。不确定,老实说。您的控制器使用哪种框架?JAX-RS?Spring?我添加了一个纯Spring控制器的示例-很抱歉,但我对Jersey不太熟悉,无法帮助您实现这一点,很抱歉。至于上传zip文件,基本上是一样的,但是您需要将
contentBody
内容类型设置为类似
application/zip
的内容类型。
/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package org.apache.http.examples.entity.mime;

import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1)  {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +
                    "/servlets-examples/servlet/RequestInfoExample");

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class Controller {

    @RequestMapping(
            value = "/uploadFile",
            method = RequestMethod.POST,
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE
    )
    public String handle(
            @RequestPart("file") MultipartFile file
    ) {
        System.out.println(file.getOriginalFilename());
        return "{}";
    }
}