以下代码片段可用于将图像上传到 Android 中的 Web 服务。从相机或其他来源获取 Bitmap 对象后,您可以压缩创建 HttpURLConnection 并将图像附加到请求正文。
try {
URL url = new URL(SERVER_POST_URL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoInput(true);
c.setRequestMethod("POST");
c.setDoOutput(true);
c.connect();
OutputStream output = c.getOutputStream();
bitmap.compress(CompressFormat.JPEG, 50, output);
output.close();
Scanner result = new Scanner(c.getInputStream());
String response = result.nextLine();
Log.e("ImageUploader", "Error uploading image: " + response);
result.close();
} catch (IOException e) {
Log.e("ImageUploader", "Error uploading image", e);
}