使用参数发送json对象

时间:2014-03-03 09:23:56

标签: android json

public void send_Json(String url, JSONObject json,String userTken) {

  try {

    HttpParams httpParams = new BasicHttpParams();


    HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpClient client = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(url);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("userToken",  userTken));

    request.setEntity(new UrlEncodedFormEntity(nameValuePairs));


    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 = .convertStreamToString(instream);
        Log.i("Read from server", "xcxcxcx");
        // Toast.makeText(context, "yeah", Toast.LENGTH_LONG).show();
    }
} catch (Throwable t) {
    Log.i("Read from server", "xcxcxcxcc  cccccccccccc");
    // Toast.makeText(context, "Request failed: " + t.toString(),
    // Toast.LENGTH_LONG).show();
 }
}   

我已编写此代码以使用我的参数发送json对象。但我需要知道如何发送它。我已经知道如何发送json对象。

1 个答案:

答案 0 :(得分:1)

nameValuePairs.add(new BasicNameValuePair("jsonKey",  json.toString()));

public void send_Json(String url, JSONObject json,String userTken) {

  try {

    HttpParams httpParams = new BasicHttpParams();


    HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    HttpClient client = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(url);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("userToken",  userTken));
 nameValuePairs.add(new BasicNameValuePair("jsonKey",  json.toString()));
    request.setEntity(new UrlEncodedFormEntity(nameValuePairs));



    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 = .convertStreamToString(instream);
        Log.i("Read from server", "xcxcxcx");
        // Toast.makeText(context, "yeah", Toast.LENGTH_LONG).show();
    }
} catch (Throwable t) {
    Log.i("Read from server", "xcxcxcxcc  cccccccccccc");
    // Toast.makeText(context, "Request failed: " + t.toString(),
    // Toast.LENGTH_LONG).show();
 }
}