【问题标题】:MultipartEntity and JsonMultipartEntity 和 Json
【发布时间】:2012-11-08 06:34:26
【问题描述】:

我想使用 MultipartEntity 将图像和 JsonObject 发送到 PHP 服务器。 这是我的代码:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString);
File file = new File(imageend);
HttpResponse response = null;
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
StringBody sb;

try {
    sb = new StringBody(json.toString());

    mpEntity.addPart("foto", cbFile);
    mpEntity.addPart("json", sb);
    httppost.setEntity(mpEntity);
    response = httpClient.execute(httppost);

我无法在 php 中阅读此内容,因为格式如下:

{\"test1\":\"Z\",\"test2\":\"1\"}

由于反斜杠,我无法在 php 中阅读此内容。如果我通过 httppost 和 bytearrayentity 发布没有图像的 json,则没有任何反斜杠,我没有问题。

【问题讨论】:

  • 您是如何创建json 对象的?
  • JSONObject json = new JSONObject();试试 { json.put("test1", test1.getText().toString()); json.put("test2", test2.getText().toString());
  • 你能看到json.toString()返回什么吗?是否包含这些反斜杠?
  • 也许你应该在你的字符串体中指定和编码?
  • @NikitaBeloglazov:很好的问题。我试图 String test = json.toString();并且没有反斜杠!所以问题应该是StringBody!但是我怎样才能读出 StringBody 呢?我切换了一个断点,但我看不到它。

标签: java android json upload multipartentity


【解决方案1】:

使用以下 PHP:

string stripslashes ( string $str )

【讨论】:

  • 我试过了,它可以工作,但如果我想上传一个带有飞溅的文本,它会删除它们,对吧?
  • 然后使用 /\ 并删除斜线
  • if (get_magic_quotes_gpc()) { function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);返回$值; } $_POST = array_map('stripslashes_deep', $_POST); $_GET = array_map('stripslashes_deep', $_GET); $_COOKIE = array_map('stripslashes_deep', $_COOKIE); $_REQUEST = array_map('stripslashes_deep', $_REQUEST); }
【解决方案2】:

也许您可以在 PHP 端使用 preg_replace 将 \" 替换为 \

【讨论】:

  • 好的,这是个好主意。但是在Java中是否有可能解决它在创建StringBody时没有设置飞溅?
  • 我们最近在一台旧服务器机器上遇到了同样的问题。服务器自动插入反斜杠。安装的 PHP 版本是 5.3.6。我们可以验证在 PHP 5.3.10 及更高版本上,反斜杠消失了。这种行为的确切原因仍然未知
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-12
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多