How to send JSON data to the server in Android
//escape the double quotes in json string
String payload="{\"action\":\"create\",\"machinetypelist\":[{\"id\":\"\",\"materialTypeId\":\"1\",\"machineinplantid\":\"MIPID-103\",\"material\":[\"1\",\"2\"]}]}"
String requestUrl="your url";
sendPostRequest(requestUrl, payload);
create sendPostRequest
method. This will work. I refered this link
How To Send json Object to the server from my android app
You need to be using an AsyncTask
class to communicate with your server. Something like this:
This is in your onCreate
method.
Button submitButton = (Button) findViewById(R.id.submit_button);
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONObject postData = new JSONObject();
try {
postData.put("name", name.getText().toString());
postData.put("address", address.getText().toString());
postData.put("manufacturer", manufacturer.getText().toString());
postData.put("location", location.getText().toString());
postData.put("type", type.getText().toString());
postData.put("deviceID", deviceID.getText().toString());
new SendDeviceDetails().execute("http://52.88.194.67:8080/IOTProjectServer/registerDevice", postData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
This is a new class within you activity class.
private class SendDeviceDetails extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes("PostData=" + params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data
}
}
The line: httpURLConnection.setRequestMethod("POST");
makes this an HTTP POST request and should be handled as a POST request on your server.
Then on your server you will need to create a new JSON object from the "PostData" which has been sent in the HTTP POST request. If you let us know what language you are using on your server then we can write up some code for you.
How to POST data in Android to server in JSON format?
I did it myself.
JSONObject returnedJObject= new JSONObject();
JSONObject KeyvalspairJObject=new JSONObject ();
JSONObject devcKeyvalspairJObject=new JSONObject ();
JSONObject capabilityJObject=new JSONObject();
JSONObject ScreenDimensionsJObject =new JSONObject();
JSONObject deviceJObject= new JSONObject();
try{
KeyvalspairJObject.put("key1","val1");
KeyvalspairJObject.put("key2","val2");
capabilityJObject.put("sms", false);
capabilityJObject.put("data", true);
capabilityJObject.put("gps", true);
capabilityJObject.put("wifi", true);
capabilityJObject.put("keyValue", KeyvalspairJObject);
ScreenDimensionsJObject.put("width", 45);
ScreenDimensionsJObject.put("height", 45);
devcKeyvalspairJObject.put("Devckey1","val1");
devcKeyvalspairJObject.put("DEVCkey2","val2");
deviceJObject.put("userAgent", "MYUserAgent");
deviceJObject.put("capabilities", capabilityJObject);
deviceJObject.put("screen", ScreenDimensionsJObject);
deviceJObject.put("keyValue", devcKeyvalspairJObject);
returnedJObject.put("clientId", "ID:1234-1234");
returnedJObject.put("carrier","TMobile");
returnedJObject.put("device",deviceJObject);
returnedJObject.put("time",1294617435);
returnedJObject.put("msisdn","1234567890");
returnedJObject.put("timezone","GMT");
}
catch(JSONException e)
{
}
and this is how we can send JSON data to server.
public String putDataToServer(String url,JSONObject returnedJObject) throws Throwable
{
HttpPost request = new HttpPost(url);
JSONStringer json = new JSONStringer();
StringBuilder sb=new StringBuilder();
if (returnedJObject!=null)
{
Iterator<String> itKeys = returnedJObject.keys();
if(itKeys.hasNext())
json.object();
while (itKeys.hasNext())
{
String k=itKeys.next();
json.key(k).value(returnedJObject.get(k));
Log.e("keys "+k,"value "+returnedJObject.get(k).toString());
}
}
json.endObject();
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
HttpResponse response =null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setSoTimeout(httpClient.getParams(), Constants.ANDROID_CONNECTION_TIMEOUT*1000);
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),Constants.ANDROID_CONNECTION_TIMEOUT*1000);
try{
response = httpClient.execute(request);
}
catch(SocketException se)
{
Log.e("SocketException", se+"");
throw se;
}
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while((line = reader.readLine()) != null){
sb.append(line);
}
return sb.toString();
}
how to send json data to server and get Json response in android?
Note : Since question doesn't ask for a specific error, this is a simple basic code to show how to send JSON data to a server (given IP)
Lets assume that we have 3 text fields with f_name
, l_name
, age
& also a button which will trigger onClick
method on button press.
Below is the code
This should be in the activity which the button is in.
public void onClick(View v) {
JSONObject payLoad = new JSONObject();
try {
payLoad.put("first_name", f_name.getText().toString());
payLoad.put("last_name", l_name.getText().toString());
payLoad.put("age", age.getText().toString());
new SendPostRequest.execute("http://123.456.789.78:8080/address1/address2", postData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
This is a new Class that responsible for send the response.
private class SendPostRequest extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String postData = "";
HttpURLConnection httpConnection= null;
try {
httpConnection= (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream outputStream= new DataOutputStream(httpURLConnection.getOutputStream());
outputStream.writeBytes("PostData=" + params[1]);
outputStream.flush();
outputStream.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char currentData = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
postData += currentData;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpConnection!= null) {
httpURLConnection.disconnect();
}
}
return postData;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Send data from android to server via JSON
To send data to server you could do this:
private void sendData(ArrayList<NameValuePair> data)
{
// 1) Connect via HTTP. 2) Encode data. 3) Send data.
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://www.blah.com/AddAccelerationData.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
//Could do something better with response.
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
}
then to send lets say:
private void sendAccelerationData(String userIDArg, String dateArg, String timeArg,
String timeStamp, String accelX, String accelY, String accelZ)
{
fileName = "AddAccelerationData.php";
//Add data to be send.
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
nameValuePairs.add(new BasicNameValuePair("userID", userIDArg));
nameValuePairs.add(new BasicNameValuePair("date",dateArg));
nameValuePairs.add(new BasicNameValuePair("time",timeArg));
nameValuePairs.add(new BasicNameValuePair("timeStamp",timeStamp));
nameValuePairs.add(new BasicNameValuePair("accelX",accelX));
nameValuePairs.add(new BasicNameValuePair("accelY",accelY));
nameValuePairs.add(new BasicNameValuePair("accelZ",accelZ));
this.sendData(nameValuePairs);
}
so then the AddAccelerationData.php file on server is:
<?php
/*
* What this file does is it:
* 1) Creates connection to database.
* 2) Retrieve the data being send.
* 3) Add the retrieved data to database 'Data'.
* 4) Close database connection.
*/
require_once '../Connection.php'; //connect to a database/disconnect handler.
require_once '../SendAPI.php'; //deals with sending querys.
$server = new Connection();
$send = new Send();
//Connect to database.
$server->connectDB();
//Retrieve the data.
$userID = $_POST['userID'];
$date = $_POST['date'];
$time = $_POST['time'];
$accelX = $_POST['accelX'];
$accelY = $_POST['accelY'];
$accelZ = $_POST['accelZ'];
//Add data to database 'Data'. //Personal method to query and add to database.
$send->sendAccelerationData($userID, $date, $time, $timeStamp, $accelX, $accelY, $accelZ);
//Disconnect from database.
$server->disconnectDB();
?>
This is an example I used recently. Just to note in the php file. I import Connection.php
this just deals with the connection to the database. So just replace that with your code for connecting to MYSQL db. Also I imported SendAPI.php (which you can just ignore)This was just my class for sending data. Basically it contained some of the querys I wanted to use. Such as sendAccelerationData(). Basically class was similar to that of stored procedures.
Related Topics
What Is the Type This String? A:1:{S:2:"En";}
Is Is Bad Practice to Use Array_Walk with MySQLi_Real_Escape_String
Image - Upload Not Responding, No Access to $_Files
Tactics for Using PHP in a High-Load Site
Optimizing Kohana-Based Websites for Speed and Scalability
How to Correctly Link PHP-Fpm and Nginx Docker Containers
Practical Zend_Acl + Zend_Auth Implementation and Best Practices
Leverage Browser Caching, How on Apache or .Htaccess
Better Way to Check Variable for Null or Empty String
What Encryption Algorithm Is Best for Encrypting Cookies
Which MySQL Datatype to Use for an Ip Address
What Does New Self(); Mean in PHP