MultipartEntity and Json

4

我想使用MultipartEntity向PHP服务器发送一张图片和一个JsonObject。以下是我的代码:

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,则没有任何反斜杠,我也就没有问题。


1
你是如何创建你的 json 对象的? - MKJParekh
你可能应该在字符串主体中指定一个编码? - njzk2
在stringbody构造函数中,如果我回忆起来 - njzk2
顺便提一下,我用了这种方法(json + multipart),虽然不是在php中,但它确实奏效了,所以我知道有可能得到合适的结果。你能发布请求转储吗?(除去完整的图像二进制部分)? - njzk2
现在,你可以告诉我如何发布请求转储吗? - t18935
显示剩余5条评论
2个回答

2
请使用以下PHP代码:
string stripslashes ( string $str )

我尝试过这个方法,它可以正常工作。但是,如果我想上传一个带有斜杠的文本,它会将它们删除,对吗? - t18935
then use /\ and remove slash - Shyam
如果(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);} - Shyam

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

好的,这是一个不错的想法。但是在Java中有没有可能解决它,使其在创建StringBody时不设置splashes呢? - t18935
我们最近在一台旧的服务器上遇到了同样的问题。服务器自动插入反斜杠。安装的PHP版本是5.3.6。我们可以验证,在PHP版本5.3.10及更高版本中,反斜杠会消失。这种行为的确切原因仍然未知。 - maddob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接