如何在没有名称 - 值对的情况下将图像发送到服务器?我知道这是基本问题,但在stackoverflow中没有明确的答案。我们怎样才能使用-POST-方法? (如您所知,名称 - 价值对已折旧)。
答案 0 :(得分:1)
public String postPhotoUploadRequest(File imageFile) {
URL url;
String response = "";
int responseCode = -1;
try {
url = new URL("your url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "binary/octet-stream");
conn.setDoOutput(true);
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setRequestMethod("POST");
DataOutputStream writer = new DataOutputStream(conn.getOutputStream());
Bitmap bmp = ImageUtils.filePathToBitmap(imageFile.getPath());
if(bmp != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, bos);
InputStream input = new ByteArrayInputStream(bos.toByteArray());
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0; ) {
writer.write(buffer, 0, length);
}
writer.flush();
writer.close();
}
responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "Response Code : " + responseCode;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}