使用Spring RestTemplate将byte []上传到SpringMVC rest端点时出现400 Bad Request

我试图将包含图像的byte []上传到我的Spring休息服务(在Spring Boot中运行,顺便说一下)作为MultipartFile,我的客户端运行Spring RestTemplate并且我得到了HttpClientErrorException:400 Bad Request.

我的终点:

@RequestMapping(value="/scale/{percent}", method= RequestMethod.POST)
public ResponseEntity scaleImage(@PathVariable("percent") float percent,
                                        @RequestParam("file") MultipartFile file) {

    try {
        if (!file.isEmpty()) {
            byte [] result = transformService.scaleImage(percent, file.getBytes());
            return getResponseEntityFromBytes(result);
        } else {
            return generateBadRequestError();
        }
    } catch (Exception e) {
        if (e instanceof InvalidOperationParameterException) {
            // TODO - populate message with bad parameters
            LOGGER.log(Level.FINE, "Invalid Parameters: ");
            return generateBadRequestError();
        } else {
            LOGGER.log(Level.SEVERE, "Exception caught: " + e.getMessage(), e);
            return generateServerError(e.getMessage());
        }
    }
}

我的Spring RestTemplate客户端:

public void scaleImage(byte[] image, float percent) throws Exception {
    String url = "http://localhost:8080/scale/" + percent;
    this.testNumberThreads=10;
    this.testNumberThreads=10;

    MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<>();
    mvm.add("file", image);
    TransformedResponse r = doPost(url, mvm);
}

private TransformedResponse doPost(String url, MultiValueMap<String, Object> mvm) {
    RestTemplate restTemplate = new RestTemplate();
    TransformedResponse xr = null;
    try {
        xr = restTemplate.postForObject(url, mvm, TransformedResponse.class);
    } catch (RestClientException e) {
        e.printStackTrace();
    }
    return xr;
}

public class TransformedResponse {
    byte[] image;

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }
}

这是我在客户端看到的异常(没有任何命中服务器):

org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:588)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:546)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:330)
    at com.me.image.xform.LoadTest.doPost(LoadTest.java:110)
    at com.me.image.xform.LoadTest.loadTestScalePercent(LoadTest.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)

为什么这个请求不会正确发布?

最佳答案
我发现了我的问题.我需要将一个AbstractResource(在本例中为ByteArrayResource)添加到我的MultiValueMap而不是原始字节数组.这是修复它的代码:

public void scaleImage(byte[] image, float percent) throws Exception {
    String url = "http://localhost:8080/scale/" + percent;

    final byte[] rawBytes = image.clone();

    MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<>();
    ByteArrayResource bar = new ByteArrayResource(rawBytes) {
        @Override
        public String getFilename() {
            return "Test-"+rawBytes.length + ".jpg";
        }
    };

    mvm.add("file", bar);
    TransformedResponse r = doPost(url, mvm);
}

转载注明原文:使用Spring RestTemplate将byte []上传到SpringMVC rest端点时出现400 Bad Request - 代码日志