Send data to server via JSON

I m new on the Android Programmer, I want to send data to the server via JSON in the following format and implement Json in this format .., and also want to receive data from the server.

{ "signup": [ { "username": "test1264", "password": "1234", "email": " example@gmail.com ", "phoneno": "223344556", "altphoneno": "12345678", "firstname": "abc", "lastname": "xyz" } ] } 

Answer:

by success: {"status":1}
on failure: {"status":0}

  • JSON for user login:
 {"login":[ {"username":"test1234", "password":"1234"} ]} Response: on success: { "user": [ { "firstname": "abc", "lastname": "xyz", "email": " example@gmail.com ", "phone": "99887766", "username": "test1234" } ] } 

In case of failure: {"error":["Auth error"]}

+6
source share
3 answers

You can use this code

 // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://fort.example.com"); JSONObject json = new JSONObject(); try { // Add your data json.put("key", "value"); StringEntity se = new StringEntity( json.toString()); httppost.setEntity(se); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); BufferedReader reader = new BufferedReader( new InputStreamReader( response.getEntity().getContent(), "UTF-8")); String jsonString = reader.readLine(); JSONTokener tokener = new JSONTokener(jsonString); JSONObject finalResult = new JSONObject(tokener); 

Remember to add this to the nonUI stream.

+3
source

You can use droidQuery to do this very easily:

 $.ajax(new AjaxOptions().url("http://fort.example.com") .type("POST") .data("\"signup\": [{" + "\"username\": \"test1264\"," + "\"password\": \"1234\"," + "\"email\": \" example@gmail.com \"," + "\"phoneno\": \"223344556\"," + "\"altphoneno\": \"12345678\"," + "\"firstname\": \"abc\"," + "\"lastname\": \"xyz\"" + "\"}]") .dataType("json") .success(new Function() { @Override public void invoke($ d, Object... args) { JSONObject json = (JSONObject) args[0]; boolean success = json.getBoolean("status"); if (success) { //handle success } else { //handle error } } }) .error(new Function() { @Override public void invoke($ d, Object... args) { AjaxError error = (AjaxError) args[0]; Log.i("Ajax", "Error " + error.status + ": " + error.reason); } })); 

You can repeat this logic for other cases, such as the web login service.

+2
source
 PostMethod method = new PostMethod(); org.apache.commons.httpclient.URI newUri = new org.apache.commons.httpclient.URI(URIstring, true); method.setURI(newUri); method.setRequestBody(JsonObj().toString()); method.setRequestHeader("Content-Type", "application/json"); org.apache.commons.httpclient.HttpClient newhttpClient = new org.apache.commons.httpclient.HttpClient(); int statusCode = newhttpClient.executeMethod(method); return method.getResponseBodyAsString(); 
0
source

Source: https://habr.com/ru/post/956360/


All Articles