人。需要有关使用multipart-data发送POST请求的帮助。
我有一个在客户端创建请求的方法。这是:
public void sendMultipart(String cmd , Employee emp) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(baseUrl + cmd);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody f = new FileBody(emp.getPhoto());
try {
StringBody s = new StringBody(emp.getLogin());
builder.addPart("name", s);
builder.addPart("file", f);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(RestTemplateRequester.class.getName()).log(Level.SEVERE, null, ex);
}
uploadFile.setHeader("Accept", "application/json");
uploadFile.setHeader("Content-type", "application/json");
uploadFile.setHeader("enctype","multipart/form-data");
uploadFile.setHeader("accept-charset","UTF-8");
//builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
//builder.addBinaryBody(emp.getLogin(), emp.getPhoto(), ContentType.MULTIPART_FORM_DATA, "file");
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
try {
HttpResponse httpResponse = httpClient.execute(uploadFile);
int status = httpResponse.getStatusLine().getStatusCode();
String str = httpResponse.getStatusLine().getReasonPhrase();
} catch (IOException ex) {
Logger.getLogger(RestTemplateRequester.class.getName()).log(Level.SEVERE, null, ex);
}
}
我还有一种方法来处理我服务器端的请求:
@RequestMapping(value = "photo", consumes = "multipart/form-data")
public @ResponseBody
void uploadFileHandler(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Create the file on server
File serverFile = new File(name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.getMessage();
}
}
}
在我的背景下:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="100000" />
</bean>
我现在遇到的问题是408错误&#34;请求超时&#34;。 我的共同目标是 - 将带文件的JSON发送到服务器。我在java中使用Web服务非常环保,所以我遇到了一些麻烦。 如果有人可以给我一些建议,那将会很棒。谢谢。
答案 0 :(得分:0)
您尝试做的不是上传文件的可接受方式(在JSON中嵌入文件)。此外,您的上传文件处理程序不适合处理JSON,而只能处理多部分文件和名称作为参数。请查看我之前使用Spring MVC Multipart和RestTemplate成功上传文件的q/a。