SpringMVC-FileUpload - запрос, отправленный клиентом, был синтаксически неверным

Я видел пару QTS на ту же тему. Но я не нашел никакой подсказки об этой ошибке.

Я работаю над POC и по ссылке ниже.http://spring.io/guides/gs/uploading-files/

Как упоминалось в приведенном выше руководстве, в автономном режиме [Spring Embeded Tomcat] он работает абсолютно нормально. Но я хочу развернуть его как веб-приложение. Итак, я создал отдельный проект SpringMVC и добавил следующий контроллер.

Файл контроллера

@Controller
public class FileUploadController {

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name, 
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = 
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

}

Я написал следующий клиент (так как я не хочу использовать RestTemplate здесь).

Сервисный клиент

private static final String URL_GET = "http://localhost:8080/SpringMVC/upload";
static String URL = "http://localhost:8080/SpringMVC/upload";

public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure("C:/DevEnvProject/eclipse/workspace_exp/OCR/log4j.properties");
    testGet();
    testPOST();
}

private static void testGet() throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(URL_GET);
    HttpResponse response = httpClient.execute(httpGet, localContext);

    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    String sResponse = reader.readLine();

} 

static void testPOST() {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(URL);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("name", new StringBody("testIcon.png"));
        entity.addPart("file", new FileBody(new File("C:/testIcon.png")));
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost, localContext);


        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse = reader.readLine();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Я не мог сделать успешный звонок в конечную точку POST. Каждый раз я получаю следующее исключение.

400 Bad Request - запрос, отправленный клиентом, был синтаксически неверным

Вызов «GET» работает нормально. Я сравнил журнал запроса «POST» с тем же запросом «POST», который я получил при тестировании с автономным подходом, как упомянуто в весеннем руководстве. Не нашел различий в части запроса.

Я знаю, что я довольно многословен в этом посте. Я хотел дать как можно больше контекстной информации. Пожалуйста помоги.

Спасибо

Ответы на вопрос(1)

Ваш ответ на вопрос