How to make POST call using HttpURLConnection with JSON data in Android - 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

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

Android: Send a file as an array of bytes using HttpURLConnection

I want to send a file via a POST HTTP request but can't find how to handle it first...
I would do this with a string parameter:
String html_params = "myparam=myparam";
byte[] outputInBytes = html_params.getBytes("UTF-8");
URL url = new URL("http://www.myurl.com/senddata.asp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "text/html");
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.close();
response = conn.getResponseCode();
However I have no idea of how to transform and send a file as an array of bytes instead of a string...
Thanks for your help

Sending JSON object to API by using http post

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

Issue while sending JSON object using HttpURLConnection POST Method

I am using HttpURLConnection class to send Post request to my server but its not working, I did the same Post call using DefaultHttpClient & its work properly, but in android org.apache.http.impl.client.DefaultHttpClient is deprecated, that's why I am using HttpURLConnection class. I don't know is anything wrong with the way I am sending the JSON object or something else.
Below is my code implementation
URL url = new URL(linkPath);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
writer.close();
out.close();
urlConnection.disconnect();

Android HTTPUrlConnection : how to set post data in http body?

I've already created my HTTPUrlConnection :
String postData = "x=val1&y=val2";
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Set-Cookie", sessionCookie);
conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
// How to add postData as http body?
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
I don't know how to set postData in http body. How to do so? Would I better use HttpPost instead?
Thanks for your help.
If you want to send String only try this way:
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
But if you want to send as Json change Content type to:
conn.setRequestProperty("Content-Type","application/json");
and now our str we can write:
String str = "{\"x\": \"val1\",\"y\":\"val2\"}";
Hope it will help,
Guruparan's link in the comment above gives a really nice answer to this question. I highly recommend looking at it. Here is the principle that makes his solution work:
From what I understand, the HttpURLConnection represents the response body as an OutputStream. So you need to call something like:
get the connection's output stream
OutputStream op = conn.getOuputStream();
write the response body
op.write( [/*your string in bit form*/] );
close the output stream
op.close();
and then carry on your merry way with the connection (which you will still need to close).

Categories

Resources