Sending a JSON Http Post Request from Android

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

}

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Sending a JSON POST request in Android

This repo is fairly good and has got all sort of http requests.
https://github.com/loopj/android-async-http

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.

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


Related Topics



Leave a reply



Submit