我在Spring引導中寫了一個寧靜的web服務,它接收文件。Spring引導使用客戶端Java代碼上傳多部分文件
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public void uploadFile(@RequestParam("file") MultipartFile uploadfile) {
System.out.println("filename: " + uploadfile.getName());
}
我們怎樣才能上傳從客戶端Java代碼的Web服務文件。而不是AJAX調用或HTML頁面形式的多部分請求?
下面的代碼使用JSON對象調用Web服務。像這樣,我想在上面的書面網絡服務中接收文件。
void clientRequest(String server_url, JSONObject fileObj){
try {
URL url = new URL(server_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(fileObj.toString().getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
logger.info("output :: " + output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
代碼中的鏈接給不工作。我已經厭倦了它。它的大部分方法都被棄用了。 –
該代碼包含4.3版本「http-client」的更新答案。 –
謝謝我厭倦了HTTP客戶端4.3它工作得更早它不起作用 –