How to Send JSON Object to the Server from My Android App

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 JSON object from ANDROID application to web server using HTTP POST?

Here You can see that how to post data using HttpURLConnection

public class sendJsonData  extends AsyncTask<String, Void, String> {

protected void onPreExecute(){}

protected String doInBackground(String... arg0) {

try {

URL url = new URL(WsUtils.BASE_URL+WsUtils.SIGNUP); // here is your URL path

JSONObject jsonObject = new JSONObject();
jsonObject.put("first_name", firstname);
jsonObject.put("last_name", lastname);
jsonObject.put("birth_date", birthdate);
jsonObject.put("email", email);
jsonObject.put("user_name", username);
jsonObject.put("password", pass);
jsonObject.put("mobile_no", mobile);
jsonObject.put("address", address);
jsonObject.put("zip_code", zipcode);
jsonObject.put("city_id", city_id);
jsonObject.put("city", cityname);
jsonObject.put("state_id", stateid);
jsonObject.put("reference_name", "xxx");
jsonObject.put("country_id", "223");
jsonObject.put("refer_by", "others");
jsonObject.put("user_role_type", "3");
Log.e("params",postDataParams.toString());

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(jsonObject));

writer.flush();
writer.close();
os.close();

int responseCode=conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader in=new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";

while((line = in.readLine()) != null) {

sb.append(line);
break;
}

in.close();
return sb.toString();

}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}

}

@Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
Log.e("response", result);
}
}

public String getPostDataString(JSONObject params) throws Exception {

StringBuilder result = new StringBuilder();
boolean first = true;

Iterator<String> itr = params.keys();

while(itr.hasNext()){

String key= itr.next();
Object value = params.get(key);

if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));

}
return result.toString();
}

Send a JSON Object from Android to PHP server with POST method and HttpURLConnection

Finally, I success to send a JSONObject to my server.

I used this code for the android part :

new Thread(new Runnable() {
@Override
public void run() {
OutputStream os = null;
InputStream is = null;
HttpURLConnection conn = null;
try {
//constants
URL url = new URL("http://192.168.43.64/happiness_barometer/php_input.php");
JSONObject jsonObject = new JSONObject();
jsonObject.put("rate", "1");
jsonObject.put("comment", "OK");
jsonObject.put("category", "pro");
jsonObject.put("day", "19");
jsonObject.put("month", "8");
jsonObject.put("year", "2015");
jsonObject.put("hour", "16");
jsonObject.put("minute", "41");
jsonObject.put("day_of_week", "3");
jsonObject.put("week", "34");
jsonObject.put("rate_number", "1");
String message = jsonObject.toString();

conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 10000 /*milliseconds*/ );
conn.setConnectTimeout( 15000 /* milliseconds */ );
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);

//make some HTTP header nicety
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

//open
conn.connect();

//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();

//do somehting with response
is = conn.getInputStream();
//String contentAsString = readIt(is,len);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
//clean up
try {
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}

conn.disconnect();
}
}
}).start();

and this one in the php part :

$json = file_get_contents('php://input');
$obj = json_decode($json);
$rate = $obj->{'rate'};
$comment = $obj->{'comment'};
$category = $obj->{'category'};
$day = $obj->{'day'};
$month = $obj->{'month'};
$year = $obj->{'year'};
$hour = $obj->{'hour'};
$minute = $obj->{'minute'};
$day_of_week = $obj->{'day_of_week'};
$week = $obj->{'week'};
$rate_number = $obj->{'rate_number'};

try
{
$bdd = new PDO('mysql:host=localhost;dbname=happiness_barometer;charset=utf8', 'utilisateur', '');
} catch (Exception $e)
{
die('Erreur : '.$e->getMessage());
}

$sql = $bdd->prepare(
'INSERT INTO rates (rate, comment, category, day, month, year, hour, minute, day_of_week, week, rate_number)
VALUES (:rate, :comment, :category, :day, :month, :year, :hour, :minute, :day_of_week, :week, :rate_number)');
if (!empty($rate)) {
$sql->execute(array(
'rate' => $rate,
'comment' => $comment,
'category' => $category,
'day' => $day,
'month' => $month,
'year' => $year,
'hour' => $hour,
'minute' => $minute,
'day_of_week' => $day_of_week,
'week' => $week,
'rate_number' => $rate_number));
}

Hope it will help someone else ;)

how to send JSON data from android to IP address for example 192.168.2.1:80?

First of all sending Json data in Url is a bad practice. Instead, as a good practice, you should send data into the body of the HTTP POST request or as url parameters in HTTP GET request.

Your problem happens because you writing unsafe characters (curly brackts) in the Url.

How to send a JSON object over Request with Android?

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);

App crashes when tries to send Json object

I ran your code on my machine what you need to do is something like that but make sure you have this in you app's build.gradle
compile 'com.android.support:support-annotations:20.0.0' if you are using old android studio version. new versions make project with builtin annotation processor

 public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
void post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure( @NonNull okhttp3.Call call,@NonNull IOException e) {
Log.e("TAG", "Failed sending message!");
//using a toast means updating the UI thread from back thread you have to call Content.runOnUiThread(new Runnable) to sync with the UI thread.
//Toast.makeText(MainActivity.this,"Failed sending message",Toast.LENGTH_LONG).show();
}

@Override
public void onResponse(@NonNull okhttp3.Call call,@NonNull Response response) throws IOException {
Log.d("TAG", "Message sent successfully!");
Log.d("TAG", response.body().string());
//Toast.makeText(MainActivity.this,"Message sent successfully!",Toast.LENGTH_LONG).show();

}
});
}

take a look at the picture I ran the code with dummy values and got to see the logcat clearly saying about thread handling issue!
Sample Image

here is the final solution for you that I made will do the trick
NOTE! you can replace "MainActivity.this" with your local Context

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
void post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure( @NonNull okhttp3.Call call,@NonNull IOException e) {
MyActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//Handle UI here
// Toast anything you like here//
}
});
}

@Override
public void onResponse(@NonNull okhttp3.Call call,@NonNull Response response) throws IOException {
MyActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//Handle UI here
//happy on Response Toast here
}
});
}

}
});
}


Related Topics



Leave a reply



Submit