Question

I have a problem and I didn't know how I can solve it. Next is my question: How can I send via Httpost this: data={"value":0, "list":[]} I tried to send this data={"value":0, "list":[]} in string but I only obtain, you need POST value from the server.

This is my code:

        HttpParams params = new BasicHttpParams();
        //params.setParameter("data", auth);
        HttpClient httpclient = new DefaultHttpClient(params);

        JSONObject auth = new JSONObject(); 
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        List<NameValuePair> nameValueP = new ArrayList<NameValuePair>(2);
        ArrayList<String> aList = new ArrayList<String>();
        nameValuePairs.add(new BasicNameValuePair("value", "0"));
        nameValuePairs.add(new BasicNameValuePair("list", aList.toString()));
        nameValueP.add(new BasicNameValuePair("data", nameValuePairs.get(0).toString()+nameValuePairs.get(1).toString()));

        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader("Content-type", "application/json");


        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        entity.setContentEncoding(HTTP.UTF_8);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entities = response.getEntity();               

        String outPut = EntityUtils.toString(entities);

outPut return error and this error said that I need to send POST element from the server.

This code should return a list, this list is a array with a differents elements.

Was it helpful?

Solution

Try something like that:

            JSONObject jsonParams = new JSONObject();
    try {

        JSONObject jsComm = new JSONObject();
        JSONObject jsLoc = new JSONObject();
        jsLoc.put("lat", (float) lat);
        jsLoc.put("long", (float) lng);
        jsComm.put("location", jsLoc);
        jsComm.put("text", txt);
        jsonParams.put("comment", jsComm);
    } catch (JSONException e2) {
        Log.d("exception", "Exception while parsing json array :" + e2.toString());
        e2.printStackTrace();
    }

then use :

AbstractHttpEntity entity = null;
entity = new ByteArrayEntity(jsonParams.toString().getBytes("UTF8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(entity);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top