0
夥計。需要使用多部分數據發送POST請求的幫助。多部分數據發送得到408狀態
我有一種方法可以在客戶端創建請求。那就是:
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錯誤「請求超時」。 我的共同目標是 - 發送JSON文件到服務器。我在Java中使用Web服務非常綠色,所以我遇到了一些麻煩。 請,如果有人能給我一點建議,那將會很棒。謝謝。