簡體   English   中英

使用base64壓縮圖像並將帖子從android發送到php

[英]Compress the image with base64 and send post from android to php

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

一些特殊字符會丟失。

為什么會這樣?

問題是base64編碼的數據可以包含'+'字符。 在x-www-form-urlencoded數據中,接收器知道'+'是空格字符的編碼。 因此,由於您不是對base64值進行URL編碼,因此任何'+'實例都會導致數據在接收時被破壞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM