1

I have code for POST query on Java

    ArrayList<HashMap<String, String>> books=SQLiteDbWrapper.getInstance().getAllBooks();
    JSONObject object=new JSONObject();
    object.put("key", KEY);

    JSONArray isbns=new JSONArray();
    for (HashMap<String, String> book:books) {
        isbns.put(book.get(SQLiteDbHelper.ISBN13_FIELD));
    }

    object.put("isbns", isbns);
    object.put("email", email);
    Log.e("log", object.toString());
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(BASE_URL+SUBMIT_SCRIPT);

    request.setEntity(new ByteArrayEntity(
        object.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(request);

I need to send JSON data into server; my web-service must get this data from $POST['json'] variable, but I don't know how can I put my JSONObject object into 'json' field for POST query? Please, help me

Anthony Graglia
  • 5,355
  • 5
  • 46
  • 75
user1078760
  • 749
  • 2
  • 11
  • 17
  • Duplicate of http://stackoverflow.com/questions/3815522/how-do-i-send-json-as-body-in-a-post-request-to-server-from-an-android-applicati – Flo Dec 30 '11 at 11:45

2 Answers2

0

You must do as follows:

String jsonValue = object.toString();
String encoded = java.net.URLEncoder.encode(jsonValue, "UTF-8");

List<NameValuePair> formData = new ArrayList<NameValuePair>();
formData.add(new NameValuePair("json", encoded));

request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestBody(formData);

response = client.execute(request);
gvaish
  • 9,374
  • 3
  • 38
  • 43
  • Thank you, but I can't make NameValuePair. It uses org.apache.http.NameValuePair right? – user1078760 Dec 30 '11 at 11:51
  • And I can't set request.setRequestBody(formData); this method is absent. – user1078760 Dec 30 '11 at 11:54
  • The code that I gave would work for HC v3. For version 4, just look up for the correct method. Technically, all you need to do is ensure that 1. It's a simple form post 2. "json" is a parameter in the body of the form posted. – gvaish Jan 02 '12 at 06:47
0

Your code looks OK. All I see is a missing content type in the HttpPost object.

request.setHeader("Content-Type", "application/json");
curioustechizen
  • 10,572
  • 10
  • 61
  • 110
  • Oops .. sorry, I misunderstood your question. My answer above will not post the value with the 'json' name. Please ignore this. – curioustechizen Dec 30 '11 at 12:29