0
我決定重寫我的舊代碼,因爲現在HttpPost,HttpResponse和HttpEntity已被棄用。這是我的舊代碼:Android:發送文件到服務器的參數
private static String uploadFile(String token, File tempFile, String uploadUrl, final String fileName)
throws IOException, ExecutionException, InterruptedException {
try {
FileInputStream in = new FileInputStream(tempFile);
byte[] fileBytes = org.apache.commons.io.IOUtils.toByteArray(in);
in.close();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("token", new StringBody(token, ContentType.TEXT_PLAIN));
builder.addPart("name", new StringBody(fileName, ContentType.TEXT_PLAIN));
builder.addPart("file", new ByteArrayBody(fileBytes, fileName));
builder.addPart("fileType", new StringBody("IMAGE", ContentType.TEXT_PLAIN));
HttpPost postRequest = new HttpPost(uploadUrl);
postRequest.setEntity(builder.build());
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
org.apache.http.HttpResponse response = httpClient.execute(postRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity urlEntity = response.getEntity();
String str = org.apache.commons.io.IOUtils.toString(urlEntity.getContent());
JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
String Url = jsonObject.get("url").getAsString();
String blobKey = jsonObject.get("key").getAsString();
return Url;
}
}
}
所以,現在我正在尋找一些替代方案。我期待HttpURLConnection,但是有什麼辦法可以添加參數來請求嗎? 我會很高興的任何幫助或暗示