user2210755
user2210755

Reputation:

Create a json string with List<NameValuePair> in android

I want to send a http request to a url with Android. I am an iOS developer and now trying to learn Android. I used to send the JSON string in iOS like below

 {"function":"login", "parameters": {"username": "nithin""password": "123456"}}

How can I send this in Android? I tried List<NameValuePair> but can't find the proper solution.

Full code of what I tried -

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("function", "login"));
        nameValuePairs.add(new BasicNameValuePair("username", "nithin"));
        nameValuePairs.add(new BasicNameValuePair("password", "123456"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

Upvotes: 2

Views: 9847

Answers (1)

Ranjit
Ranjit

Reputation: 5150

I think JsonStringer is easy and useful for you here..

Try this:

   HttpPost request = new HttpPost(URL);
   request.setHeader("Accept", "application/json");
   request.setHeader("Content-type", "application/json");
   JSONStringer vm;
   try {
         vm = new JSONStringer().object().key("function")
        .value(login).key("parameters").object()
        .key("username")
        .value(nithin).key("password").value("123456")
        .endObject().endObject();
  StringEntity entity = new StringEntity(vm.toString());
  request.setEntity(entity);
  HttpClient httpClient = new DefaultHttpClient();
  HttpResponse response = httpClient.execute(request);

Upvotes: 2

Related Questions