2 回答

TA貢獻1712條經驗 獲得超3個贊
當查看您的 curl 命令行時,它表明該文件需要作為請求發送multipart/form-data
。這實際上是一種在需要時格式化數據的復雜方法。
您需要發送的格式示例是:
標頭:
Content-Type:?multipart/form-data;?boundary=AaB03x身體:
--AaB03x Content-Disposition:?form-data;?name="files"; ?filename="file1.txt"Content-Type:?text/plain ...?contents?of?file1.txt?... --AaB03x--
目前,您的代碼正在將文件作為 POST/GET 格式的請求發送,這不起作用,因為后端不希望這樣做。
為了解決這個問題,我們需要將源文件格式化成后端需要的格式,一旦知道“boundary”頭選項只是一個隨機生成的值,發送請求就變得容易多了。
String boundary = "MY_AWESOME_BOUNDARY"
http_conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);??
try(DataOutputStream outputStream = new DataOutputStream(http_conn.getOutputStream())) {
? ? File file_obj = new File(this.file);? ? ? ? ? ? ? ? ? ? ??
? ? // Write form-data header? ?
? ? outputStream.write(("--" + boundary + "\r\n").getBytes("UTF-8"));
? ? outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file1.txt\"\r\n").getBytes("UTF-8"));
? ? outputStream.write(("Content-Type: text/plain\r\n").getBytes("UTF-8"));
? ? outputStream.write(("\r\n").getBytes("UTF-8"));
? ? // Write form-data body
? ? Files.copy(file_obj.toPath(), outputStream)
? ? // Write form-data "end"
? ? outputStream.write(("--" + boundary + "--\r\n").getBytes("UTF-8"));
}
// Read backend response here
try(InputStream inputStream = http_conn.getInputStream()) {? ? ? ? ? ?
? ? BufferedReader bufferedReader = new BufferedReader(new?
? ? InputStreamReader(inputStream));
? ? StringBuilder lines = new StringBuilder(); // StringBuilder is faster for concatination than appending strings? ? ? ? ? ?
? ? while ((line = bufferedReader.readLine()) != null) {
? ? ? ? lines.append(line);? ? ? ? ? ? ? ??
? ? }
? ? System.out.println(lines);
}
請注意,我使用了“try-with-resource”塊,這些塊確保在您使用完它們后關閉和處置任何外部資源,與內存量相比,通常操作系統的開放資源限制非常低你的程序有,所以發生的是你的程序可能會出現奇怪的錯誤,這些錯誤只會在運行一段時間后或用戶在你的應用程序中執行某些操作時發生

TA貢獻1811條經驗 獲得超4個贊
以上對我沒有用,所以我切換到不同的包(okhttp3),這是對我有用的:
File file_obj = new File(this.file);
String authorization = "my authorization string";
Proxy webproxy = new Proxy(Proxy.Type.HTTP, new
InetSocketAddress("proxy", <port>));
OkHttpClient client = new OkHttpClient.Builder().proxy(webproxy).build();
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "filename",
RequestBody.create(MediaType.parse("application/octet-stream"), file_obj)).build();
Request request = new Request.Builder().header("Authorization", authorization).url(this.url).post(requestBody).build();
try (Response response = client.newCall(request).execute()){
if(!response.isSuccessful()) return "NA";
return (response.body().string());
}
添加回答
舉報