2017-09-10 63 views
0

我有一个来自摄像头的图片作为位图。 这张照片我要发送的JPEG服务器通过HTTP POST,这样的事情:如何通过http post发送位图到服务器

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

我从蔚蓝

//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

您的PIC转换为字符串base_64并发送 –

+0

如何才能把它转换为base64? – tobias

+2

https://stackoverflow.com/questions/7360403/base-64-encode-and-decode-example-code或https://stackoverflow.com/questions/9920967/android-post-base64-string-to-php –

回答

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); 
} 
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()); 
} 
相关问题