我试图将两个字符串和一个* .jpg(Base64)文件发布到Spring servlet,我收到了一个http 400错误,我知道这个错误是由于@RequestParam
被设置为required = true
@RequestMapping(value = "blurred-url/start", method = RequestMethod.POST)
public ResponseEntity<String> start(@RequestParam(value = "base64Image", required = true) final String base64Image,
@RequestParam(value = "transactionId", required = true) final String transactionId,
@RequestParam(value = "counterSignature", required = true) final String counterSignature)
我使用以下代码将图像文件编码为Base64(现在为硬编码)
public static String getImage(){
File file = new File("c://nota.jpg");
byte[] imageByteArray = null;
String imageDataString = null;
try {
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
imageDataString = encodeImage(imageData);
} catch (IOException e) {
e.printStackTrace();
}
return imageDataString;
}
/**
* Encodes the byte array into base64 string
*
* @param imageByteArray - byte array
* @return String a {@link java.lang.String}
*/
public static String encodeImage(byte[] imageByteArray) {
return Base64.encodeBase64URLSafeString(imageByteArray);
}
我已经尝试过使用Apache HttpClient的许多不同方法,现在我正在使用MultipartEntityBuilder
,但仍然无法使其正常工作,代码如下
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/server-name/" +
"blurred-url.action");
StringBody base64Image = new StringBody("123", ContentType.TEXT_HTML);
StringBody transactionId = new StringBody(jsonObj.get("signature").getAsString(), ContentType.TEXT_PLAIN);
StringBody signature = new StringBody(jsonObj.get("signature").getAsString(), ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("base64Image", base64Image)
.addPart("counterSignature", signature)
.addPart("transactionId", transactionId)
.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
if(response.getStatusLine().getStatusCode() == 200){
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
JsonObject jsPost = getJsonObjectFromStream(resEntity.getContent());
System.out.println("success: "+jsPost.get("success"));
}else{
HttpEntity resEntity = response.getEntity();
StringWriter writer = new StringWriter();
IOUtils.copy(resEntity.getContent(), writer,Charset.defaultCharset());
System.out.println(response.getStatusLine());
System.err.println(writer.toString());
}
} finally {
response.close();
}
} finally {
httpclient.close();
}
我认为文件的大小有问题,我认为,因为如果我只是将图像编码的字符串更改为更短的字符串,如&#34; 123&#34;请求通过,现在我正在使用400 KB图像,任何想法?