Sending JSON object to API by using http post - android

I want to add header "Content-Type" "application/json". But I am not been able to do this due to api 23 in android.
OutputStream os= null;
os=httpclient.getOutputStream();
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os));
JSONObject jsonobj = new JSONObject();
jsonobj.put("Name","alpha");
jsonobj.put("Status","Active");
jsonobj.put("Type","Admin");
jsonobj.put("Address","beta");
jsonobj.put("Password","333");
jsonobj.put("PhoneNumber",123);
bw.write(jsonobj.toString());
os.close();

I assume that you are trying to make a network call to some API which expects you to add Headers to the HTTP calls you are making and the content-type data is JSON.
If that is your case then you would have to specify the Headers to the instance to respective class with which you are trying to connect..
for example if you are using HttpURLConnection
then it would look like this
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // hear 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();
and when you are posting some data to the instance of the HttpURLConnection you can do it like this...
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("para_1", "arg_1");
jsonObject.addProperty("para_2", "arg_2");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();

Related

Unable to send json with HttpURLConnection

I have been looking at this over a week now and i cant find where the null pointer problem lies, this is bugging me completely and the teacher Google is not very helpful. I cant find what the real problem here...and its driving nuts! :/
I am trying to send a notification to Firebase and it does not go beyond the streamwriter, i have checked that conn is not null or the json but they are all looking good. If i use a RESTclient i can send a message successfully with correct ID key and message and it is recived by the app. The emulated phone has internet connection.
The error thrown in run looks like this:
com.android.okhttp.internal.huc.HttpURLConnectionImpl:https://fcm.googleapis.com/fcm/send. Attempt to invoke interface method 'void om.android.okhttp.internal.http.HttpStream.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference.
my code:
String FCM_URL = "https://fcm.googleapis.com/fcm/send";
URL url = new URL(FCM_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
//set method as POST or GET
conn.setRequestMethod("POST");
conn.setConnectTimeout(3000);
//pass FCM server key
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
//Specify Message Format
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
//Create JSON Object & pass value
JSONObject infoJson = new JSONObject();
infoJson.put("body", message);
infoJson.put("title", "Test send:");
JSONObject json = new JSONObject();
json.put("to", tokenId);
json.put("collapse_key", "type_a");
json.put("notification", infoJson);
//Add data to json string
JSONObject datacon = new JSONObject();
datacon.put("body","First notification");
datacon.put("title", "Collapsing A");
datacon.put("key_1","Data for key 1");
datacon.put("key_2","Hello, test two");
json.put("data", datacon);
BufferedWriter out =
new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out.write(json.toString());
out.flush();
out.close();
Any help or pointers would be greatly appreciated!
It seems there is a typo, set instead of add
conn.setRequestProperty("Content-Type", "application/json");
and after that, to be able to write
conn.connect();

How to connect Android to Node.js?

I'm trying to connect Android to Node.js, i have a server running in port 3000 to my localhost, when i try past data from POST method using postman, it works perfectly, but when i do the same with Android whit class HttpUrlConnection this is the result.
Result in the server
this is the code from Node.js
router.post('/', (req, res)=>{
console.log(req.query);
res.send({
mensaje: 'I am from usuario routes'
});
});
and this is from android
URL obj = new URL("http://192.168.1.107:3000/");
JSONObject jsonObject = new JSONObject();
jsonObject.put("image", "imagen");
String data = jsonObject.toString();
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
//con.setDoInput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setFixedLengthStreamingMode(data.getBytes().length);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.connect();
OutputStream out = new BufferedOutputStream(con.getOutputStream());
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
wrt.append(data);
wrt.flush();
wrt.close();
out.close();
con.disconnect();
You should write the data before connecting to the server:
URL obj = new URL("http://192.168.1.107:3000/");
JSONObject jsonObject = new JSONObject();
jsonObject.put("image", "imagen");
String data = jsonObject.toString();
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setFixedLengthStreamingMode(data.getBytes().length);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
OutputStream os = con.getOutputStream();
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
wrt.append(data);
wrt.flush();
wrt.close();
os.close();
con.connect();
The request in Android is perfect, but in Node i was not using a middleware to convert the body, i used body-parse module and it works.

Parameters from Android call not available through params hash

Typically, when I make a POST or GET HTTP call from a web app, the hash is available directly from the params hash:
#user = User.find(params[:id])
However, I have sent content type 'application/json' from an Android app, as so:
JSONObject holder = new JSONObject();
JSONObject userObj = new JSONObject();
userObj.put("username", params.get("name"));
userObj.put("uid", params.get("uid"));
userObj.put("image", params.get("image"));
userObj.put("provider", params.get("provider"));
holder.put("user", userObj);
query = holder.toString();
url = new URL("http://10.0.2.2:3001/users/auth/facebook/callback.json ");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
And when I looked at the logs, the data is nicely formatted:
Processing by OmniauthCallbacksController#facebook as JSON
Parameters: {"user"=>{"username"=>"John Dough", "uid"=>"11111222444", ...
However, I cannot access the params hash as so:
params_user # => nil
def params_user
params[:user].permit!
end
Why can I not access the params hash when it is clearly available?
If I try to access it like this:
params.parameters['user']
It tells me the parameters method of params is protected. But that is the only place I see my data when I use the debugger.
NoMethodError (protected method `parameters' called for #<ActionController::Parameters:0x007fc51d1f9e08>):
not sure which version of Rails you're using but in modern Rails you do this:
def params_user
params.require(:user).permit(:email, :name, :other_attributes)
end

Some character didn't post with Json Post - getting 500 reponse

I have prepared one API, and I want to send one specific data with json posting.
My code works fine during working with Fiddler or site side.
But the problem is why some character didn't send, when we use Android version as a client device.
For example:
string a="mn✈" // correct on any device (android,site,Fiddler,...)
string b="mn✉" //correct on any device except(android) //getting 500 reponse
String requestURL = Utils.SERVER_URL + "PostJsonFeatures";
HttpURLConnection conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject postDataParams = new JSONObject();
postDataParams.put("Features", getAttributes());
postDataParams.put("productId", productId);
postDataParams.put("groupId", catId);
postDataParams.put("brandId", PrefManager.getInstance(context).getCompanyId());
postDataParams.put("languageId", PrefManager.getInstance(context).getLanguageApi());
DataOutputStream printout = new DataOutputStream(conn.getOutputStream ());
printout.write(postDataParams.toString().getBytes());
printout.flush ();
printout.close ();
You can decode to string and pass in url.
String parseString = URLDecoder.decode(URLEncoder.encode(myString, "UTF-8"), "ISO-8859-1");

How to make POST call using HttpURLConnection with JSON data in Android

please help me out with this problem.
I want to make a POST call with JSON data that should appear in body to request but i am not able to do that. I made POST call and getting data but data is not in JSON format.
Code :
data = "{'mobile':'"+mobile_number+"','password':'"+mypassword+"'}";
byte[] dataPost = data.getBytes();
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setRequestProperty("Accept", "application/json");
//urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "UTF8");
urlConnection.setUseCaches(false);
OutputStream os = urlConnection.getOutputStream();
os.write(dataPost);
os.close();
Result is coming like below
body:
{'a':'b','c':'d'}:""
Please Help me. i am new to android Development.
Thanks

Categories

Resources