douweicheng5532 2019-03-08 12:53
浏览 195

为什么不能使用httpurlconnection发布整个base64字符串?

I want to upload the image to the server.

  1. I got the bitmap of the image and encoded it to base64.
  2. I convert the base64 of the image to a string using the encodeToString method.
  3. I post the string to PHP using httpurlconnection. Actually, I got the string from PHP which is not the whole string. I don`t get any error. Please give me feedback!
public String httpURLConnectionPost(final String urlString){    
        String result="";    
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.connect();

            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.download);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            String encodedImage = Base64.encodeToString(imageBytes, Base64.NO_CLOSE);

            String body= "image="+encodedImage;

            Log.d("serverPostData","body = " +body);

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();

            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();

                StringBuilder stringBuilder = new StringBuilder();
                String line;

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                while ((line = br.readLine()) != null) {
                    stringBuilder .append(line);
                }
                result = stringBuilder .toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

The php got the string and decode it.

<?php

include("mysqli_connect.php");

$image= $_POST['image'];

$a = uniqid() ; 

$ImagePath = "good/$a.JPEG";

$ServerURL = "https://172.30.10.1/$ImagePath";

 $InsertSQL = "INSERT INTO Photoshop(photo) VALUES('$ServerURL')" ;

 if(mysqli_query($connect, $InsertSQL)){
          file_put_contents($ImagePath,base64_decode($image));
          echo $image;          
 }else{
    echo "failed";
}

mysqli_close();
?>
  • 写回答

2条回答 默认 最新

  • dongtuwu8548 2019-03-08 13:02
    关注

    Try this to convert image to base64:

    Uri uri = data.getData();
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
    String encodedImageData = getEncoded64ImageStringFromBitmap(bitmap);
    

    Now pass the data in API:

     JsonObject data1 = new JsonObject();
     data1.addProperty("imageData", "data:image/png;base64," + encodedImageData);
    

    Now set ImageBitmap:

    image.setImageBitmap(bitmap);
    

    Here is the method:

    private String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
    
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] byteFormat = stream.toByteArray();
        // get the base 64 string
        String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
    
        return imgString;
    }
    

    And for HttpUrlConnection try this...

    jsonObject = new JSONObject();
    jsonObject.put("imageString", encodedImage);
    String data = jsonObject.toString();
    String yourURL = "yourphpfileurl";
    URL url = new URL(yourURL);
    
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setFixedLengthStreamingMode(data.getBytes().length);
    connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    
    OutputStream out = new BufferedOutputStream(connection.getOutputStream());
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
    writer.write(data);
    writer.flush();
    writer.close();
    out.close();
    connection.connect();
    
    InputStream in = new BufferedInputStream(connection.getInputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(
                    in, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            in.close();
            String result = sb.toString();
            connection.disconnect();
    

    Hope this one will work for you...

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog