简体   繁体   中英

how to pass json array to HttpPost?

I am calling a webservice post request in android with HttpPost I have a json array,its working good with string but when I pass a JsonArray like below its not working any suggestion will be greatly thanked

like this

    JSONObject jo=new JSONObject();
     jo.put("title","some string value");
     jo.put("players","[1,2,3]");

    HttpResponse rr=  makeRequest(url,jo.toString());
    json_string = EntityUtils.toString(rr.getEntity());

/// my request function

 public HttpResponse makeRequest(String uri, String json) {
    try {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(new StringEntity(json));
        SharedPreferences sf=this.getSharedPreferences("all", 0);
        String authToken=sf.getString("authToken","");          
        httpPost.setHeader("authtoken", authToken);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        return new DefaultHttpClient().execute(httpPost);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Use this

try {
    JSONObject json = new JSONObject();
    json.put("UserName", "test2");
    json.put("FullName", "1234567");
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,
            TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpClient client = new DefaultHttpClient(httpParams);
    //
    //String url = "http://10.0.2.2:8080/sample1/webservice2.php?" + 
    //             "json={\"UserName\":1,\"FullName\":2}";
    String url = "http://10.0.2.2:8080/sample1/webservice2.php";

    HttpPost request = new HttpPost(url);
    request.setEntity(new ByteArrayEntity(json.toString().getBytes(
            "UTF8")));
    request.setHeader("json", json.toString());
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    // If the response does not enclose an entity, there is no need
    if (entity != null) {
        InputStream instream = entity.getContent();

        String result = RestClient.convertStreamToString(instream);
        Log.i("Read from server", result);
        Toast.makeText(this,  result,
                Toast.LENGTH_LONG).show();
    }
} catch (Throwable t) {
    Toast.makeText(this, "Request failed: " + t.toString(),
            Toast.LENGTH_LONG).show();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM