【问题标题】:Not able to send base64 string images to asp.net web service via JSON in android无法通过 android 中的 JSON 将 base64 字符串图像发送到 asp.net Web 服务
【发布时间】:2013-04-10 13:28:18
【问题描述】:

我在 ASP.net 中创建了一个 RESTful 的 Web 服务。我想从一个 Android 应用程序使用这些服务。基本上,我使用 Android 的默认库以 JSON 格式发送请求并获得响应。

这是我的代码:

public class PostImagesHandler {
    final static String TAG = "WebHandlerHttpPost";
    Context context;
    ImagesBean imageBean;

    public String postImagesRequest(String URL, Context context,
            ImagesBean imgBean) {
        this.context = context;
        String result = null;
        this.imageBean = imgBean;

        try {
            HttpPost request = new HttpPost(URL);
            System.out.println("WHAT IS URL :: " + URL);
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");
            request.addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
            request.addHeader("Pragma", "no-cache"); // HTTP 1.0.
            request.addHeader("Expires", "0"); // Proxies.


                     Bitmap bm = BitmapFactory.decodeFile("sdcard/dotTest9.jpg");
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             bm.compress(Bitmap.CompressFormat.JPEG, 90, baos);
             byte[] bytes_ = baos.toByteArray();

            String image_str = Base64.encodeToString(readFile().getBytes(),
                    Base64.NO_WRAP);
            appendLog(image_str);

            JSONStringer userJson = new JSONStringer().object()
            .key("objPostSectionImages").object().key("ID")
            .value("1").key("SUB_ID").value("1").key("MainTaskId")
            .value("1").key("ImageBase64").value(image_str)
            .key("actualAuditDate").value(getCurrentDateTime()).endObject()
             endObject();


            Log.d(TAG, "SECTION IMAGE STRING :: " + userJson.toString());

            StringEntity entity = new StringEntity(userJson.toString(), "UTF-8");
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            entity.setContentType("application/json");
            request.setEntity(entity);

            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, 30000);
            HttpConnectionParams.setSoTimeout(params, 10000);

            // Send request to WCF service
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);

            if (response != null) {
                StringBuilder sb = new StringBuilder();
                BufferedReader rd = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));

                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line + "\n");
                }

                result = sb.toString();
                Log.d(TAG, "AUDIT SECTION IMAGES Response: " + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public void appendLog(String text) {
        File logFile = new File("sdcard/dotTest7.txt");
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            // BufferedWriter for performance, true to set append to file flag
            BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
                    true));
            buf.append(text);
            // buf.newLine();
            buf.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @SuppressLint("SimpleDateFormat")
    public static String getCurrentDateTime() {
        return new SimpleDateFormat("MM-dd-yyyy").format(Calendar.getInstance()
                .getTime());
    }
}

我可以通过这种方式发送小图像,但是在发送大图像(超过 5 KB)时,我遇到了问题。有时我会收到“请求错误”,有时它会起作用。

【问题讨论】:

  • 是否有任何理由不应该将图像流式传输到服务而不是转换为 Base64 字符串?
  • 我正在创建一个 json 对象,base64 是该对象的一个​​参数。然后这个对象被传递给基于 REST 的 WCF。 WCF 需要 base64 字符串。
  • 你可以使用multipart upload
  • 我也想过使用 Multipart。但我正在寻找解决方案,据我个人所知,通过 JSON 发送 10 KB BASE64 字符串有什么问题。我的问题是:是否需要通过 Multipart 发送 10KB BASE64 字符串图像?
  • 对于较大的图像,您肯定会在 Android 上耗尽内存。框架不赞成大字符串。如果您使用分段上传,您不妨流式传输 byte[] 而不是 base64 字符串。

标签: java android json base64 http-post


【解决方案1】:

也许您的 ASP.NET 网络服务在 base64 字符串中转义了正斜杠?这使得从普通应用程序的角度来看,这些数据被破坏了。

在小图像中,base64 转换后得到/ 符号的概率明显低于大图像,因此您会遇到这种随机错误情况。

您可以检查您的服务结果字符串中是否有 /\ 符号并将它们替换为 / 并检查它是否有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 2019-04-11
    • 2013-12-06
    • 2014-04-25
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    相关资源
    最近更新 更多