【发布时间】:2017-09-22 12:06:10
【问题描述】:
我决定重写我的旧代码,因为 HttpPost、HttpResponse 和 HttpEntity 现在已被弃用。这是我的旧代码:
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,但有没有办法向请求添加参数? 我会很高兴得到任何帮助或提示
【问题讨论】:
标签: android post httpurlconnection