如何通过HTTP帖子将位图发送到服务器



我从相机上有一张图片作为位图。我想通过HTTP帖子将此图片发送到服务器,类似的内容:

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);

将您的位图转换为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);
}

首先将位图转换为JPEG。对于将位图转换为JPEG,您可以参考: - 如何将位图转换为Android中的JPEG文件?

之后,使用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());
}

最新更新