如何通过http post将位图发送到服务器

时间:2017-09-10 14:21:25

标签: android image http

我有一张来自相机的照片作为位图。 这张图片我想通过http Post发送给服务器jpg,如下所示:

Bitmap photo;
StringEntity reqEntity = new StringEntity(photo);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(request);

我有来自azure的代码

//Request headers. 
request.setHeader("Content-Type", "application/json"); request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey); 
// Request body. 
StringEntity reqEntity = new StringEntity("{\"url\":\"upload.wikimedia.org/wikipedia/comm‌​ons/c/c3/…\"}"); 
request.setEntity(reqEntity);

2 个答案:

答案 0 :(得分:0)

将您的位图转换为base64字符串,尝试下面的代码并将该字符串发布到服务器

public static String encodeTobase64(Bitmap image)
{
   Bitmap immagex=image;
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   immagex.compress(Bitmap.CompressFormat.PNG, 100, baos);
   byte[] b = baos.toByteArray();
   String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
   return imageEncoded;
}

public static Bitmap decodeBase64(String input)
{
   byte[] decodedByte = Base64.decode(input, 0);
   return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}

答案 1 :(得分:0)

首先将位图转换为jpeg。 要将位图转换为jpeg,您可以参考: - How to convert a bitmap to a jpeg file in Android?

之后使用multipart实体将文件发送到服务器。

将文件发送到服务器: -

InputStream is = null;
String response ="";
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("profile_pic", new FileBody(new File(profileImagePath)));

try {

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    httpPost.setEntity(mpEntity);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    response = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}