How to send JSON parameters as a web service request in Android?

Possible duplicate:
How to send a JSON object via Request from Android?

Since I am new to Android development, I am faced with the problem of sending requests to a web service in the form of JSON. Googling, I found the following code to send requests using parameters. Here is the Java class we are sending as:

Main.java

RestClient client = new RestClient(LOGIN_URL); client.AddParam("Email", _username); client.AddParam("Passwd", _password); try { client.Execute(RequestMethod.POST); } catch (Exception e) { e.printStackTrace(); } String response = client.getResponse(); 

But here I want to send parameters in a JSON form, for example, for example, I want to send parameters in this form:

 { "login":{ "Email":_username, "Passwd":_password, } } 

So can anyone help me? How to send parameters in JSON form?

+2
java json android web-services
source share
1 answer

The example you publish uses a “library” compiled by someone as a wrapper for the Apache class HttpClient. This is not particularly good. But you don’t need to use this shell at all, the HttpClient itself is dead just to use. Here is an example of code you can build:

 final String uri = "http://www.example.com"; final String body = String.format("{\"login\": {\"Email\": \"%s\", \"Passwd\": \"%s\"}", "me@email.com", "password"); final HttpClient client = new DefaultHttpClient(); final HttpPost postMethod = new HttpPost(uri); postMethod.setEntity(new StringEntity(body, "utf-8")); try { final HttpResponse response = client.execute(postMethod); final String responseData = EntityUtils.toString(response.getEntity(), "utf-8"); } catch(final Exception e) { // handle exception here } 

Note that you are most likely to use the JSON library to serialize POJOs and create a JSON request.

+3
source share

All Articles