使用base64压缩图像并将帖子从android发送到php

时间:2017-11-29 08:15:00

标签: php android base64

ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
mBitmapProfile.compress(Bitmap.CompressFormat.JPEG, 100, bytearray);
String base64 = Base64.encodeToString(bytearray.toByteArray(), Base64.DEFAULT);
String data = URLEncoder.encode("SOURCE", "UTF-8") + "=" base64;

String result = getHttpData("http://example/p.php", data);


private String getHttpData(String httpUrl, String param) {
        String urlString = httpUrl;
        String data = param;

        try {
            URL url = new URL(urlString);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
            // urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);

            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());

            wr.write(data);
            wr.flush();

            int responseCode = urlConnection.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String response = "";
                String line = "";
                while ((line = br.readLine()) != null) {
                    response+=line;
                }
                return response;
            }
        } catch(MalformedURLException e){
            e.printStackTrace();
            return null;
        } catch(IOException e) {
            e.printStackTrace();
            return null;
        }
        return "";
    }

base64编码后的图像

使用POST,从Android向PHP发出请求会导致问题。

离)

  

android发送数据:/ 9j / 4AAQSkZJRgABAQAAAQABAAD / 2wBDAAEBA + BAQEBAQE ==

     

php接收数据:/ 9j / 4AAQSkZJRgABAQAAAQABAAD / 2wBDAAEBABAQEBAQE

丢失了一些特殊字符。

为什么会这样?

1 个答案:

答案 0 :(得分:0)

问题是base64编码数据可以包含“+”字符。在x-www-form-urlencoded数据中,接收者知道'+'是空格字符的编码。因此,由于您不是对base64值进行URL编码,因此任何“+”实例都会导致数据在收到时被破坏。