4

I want to send an image and a JsonObject to an PHP Server with MultipartEntity. Here is my Code:

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); 

I can't read this in php because the format is like:

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

I'm not able to read this in php because of the backslashes. If I post json without image over httppost and bytearrayentity there aren't any backslashes and I have no problem.

10
  • 1
    how you are creating your json object? Commented Nov 20, 2012 at 8:22
  • JSONObject json = new JSONObject(); try { json.put("test1", test1.getText().toString()); json.put("test2", test2.getText().toString()); Commented Nov 20, 2012 at 8:34
  • Can you see what does json.toString() return? Does contain these backslashes? Commented Nov 20, 2012 at 8:41
  • may be you should specifcy and encoding in your stringbody ? Commented Nov 20, 2012 at 8:53
  • @NikitaBeloglazov: Great question. I tried to String test = json.toString(); and there are no backslashes! So the problem should be the StringBody! But how can I read out the StringBody? I toggled a breakpoint but I can't see it. Commented Nov 20, 2012 at 8:56

2 Answers 2

2

Use following PHP:

string stripslashes ( string $str ) 
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this and it works, but if I want to upload an text with splashes in it it will delete them, right?
then use /\ and remove slash
if (get_magic_quotes_gpc()) { function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $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); }
0

Maybe you can just replace the \" by \ using preg_replace on the PHP side

2 Comments

Ok that's a good idea. But isn't there any possibility to resolve it in Java that it doesn't set the splashes when creating StringBody?
We had recently the same problem on an old server machine. The server automatically inserted the backslashes. The PHP version installed was 5.3.6. We could verify that on PHP versions 5.3.10 and higher the backslashes disappeared. The exact reason for this behavior is still unknown

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.