AndroidDev AndroidDev - 6 months ago 9
JSON Question

How to send a JSON object over Request with Android?

I want to send the following

JSON
text
{"Email":"aaa@tbbb.com","Password":"123456"}
to a web service and read the response. I know to how to read
JSON
. The problem is that the above
JSON
object must be sent in a variable name
jason
.

How can I do this from android? What are the steps such as creating request object, setting content headers, etc.

Answer

Android doesn't have special code for sending and receiving HTTP, you can use standard Java code. I'd recommend using the Apache HTTP client, which comes with Android. Here's a snippet of code I used to send an HTTP POST.

I don't understand what sending the object in a variable named "jason" has to do with anything. If you're not sure what exactly the server wants, consider writing a test program to send various strings to the server until you know what format it needs to be in.

int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
    postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);