How to Send a Json Object Over Request With Android

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.

Android POST request with JSON

Solved:

changed

os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));

to

os.writeBytes(jsonParam.toString());

And put the code in a thread (thanks to @Ravi Sanker)

Working code:

public void sendPost() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(urlAdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);

JSONObject jsonParam = new JSONObject();
jsonParam.put("timestamp", 1488873360);
jsonParam.put("uname", message.getUser());
jsonParam.put("message", message.getMessage());
jsonParam.put("latitude", 0D);
jsonParam.put("longitude", 0D);

Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());

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

Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());

conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});

thread.start();
}

Sending json object via http post method in android

Define a class AsyncT and call it in onCreate method using:

AsyncT asyncT = new AsyncT();
asyncT.execute();

Class definition:

class AsyncT extends AsyncTask<Void,Void,Void>{

@Override
protected Void doInBackground(Void... params) {

try {
URL url = new URL(""); //Enter URL here
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
httpURLConnection.connect();

JSONObject jsonObject = new JSONObject();
jsonObject.put("para_1", "arg_1");

DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}


}

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

Volley Post request ,Send Json object in Json array request

Seems like it was removed in recent volley version but you can easily modify this constructor and add to JsonArrayRequest.

public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}

How to send json object inside another json object using Retrofit in android?

I think your model classes must be like this

Employee.java

public class Employee implements Serializable
{

@SerializedName("firstName")
@Expose
private String firstName;
@SerializedName("emailId")
@Expose
private String emailId;
@SerializedName("userType")
@Expose
private UserType userType;
@SerializedName("floor")
@Expose
private Floor floor;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public UserType getUserType() {
return userType;
}

public void setUserType(UserType userType) {
this.userType = userType;
}

public Floor getFloor() {
return floor;
}

public void setFloor(Floor floor) {
this.floor = floor;
}

}

----------------------Floor.java-------------------------

public class Floor implements Serializable
{

@SerializedName("id")
@Expose
private String id;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

}

------------------UserType.java-------------------------

public class UserType implements Serializable
{

@SerializedName("id")
@Expose
private String id;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

}

It is self explanatory I think

Sending Post Request to URL with json object Data and Headers from Android

I solved the problem i debbuged the json in Logcat amd found it was not correctly structured after making it correct it starts working, Letme Mention i am specifically using this for firebase notification through api .

i did like this :

public static String makeRequest(String id) throws JSONException {
HttpURLConnection urlConnection;
JSONObject json = new JSONObject();
JSONObject info = new JSONObject();
info.put("title", "Notification Title"); // Notification title
info.put("body", "Notification body"); // Notification body
info.put("sound", "mySound"); // Notification sound
json.put("notification", info);
json.put("to","INSTANCE ID FETCHED FOR SIGNLE DEVICE HERE");
Log.e("deviceidkey==> ",id+"");
Log.e("jsonn==> ",json.toString());
String data = json.toString();
String result = null;
try {
//Connect
urlConnection = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send").openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "key=YOUR FIREBASE SERVER KEY");
urlConnection.setRequestMethod("POST");
urlConnection.connect();

//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();

//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

String line = null;
StringBuilder sb = new StringBuilder();

while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}

bufferedReader.close();
result = sb.toString();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

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



Related Topics



Leave a reply



Submit