Unable to send json with HttpURLConnection - android

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

Related

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

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

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

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

Not able to insert data to mysql via servlet

I am trying to insert data to a mysql table using the below methods but am not able to do so. Any idea on where I may be going wrong?
Method 1: Using HTTPClient to directly access the URL. Below is the code:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://<lclhst>/GnPServlet/GetNpostServlet/? account=1&password=123");
HttpResponse execute = client.execute(httpPost);
Method 2: Using URL connection to directly access the URL. Below is the code:
URL url = new URL("http://<lclhst>/GnPServlet/GetNpostServlet/? account=1&password=123");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/octet-stream");
conn.connect();
Method 3: Using Arraylist to pass values.
When i run the URL from the browser i get the success message "Inserted" and the data is inserted into the DB. But the same when tried through the app does not insert data. Below is the servlet code:
private String accountLookup(String acct, String pwd)
{
Connection con = null;
Statement st = null;
StringBuffer msgb = new StringBuffer("");
try
{
// These will vary depending on your server/database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbone?user=root&password=root");
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into accttbl(address, description, time) values ('test 07-jul',ok,12:12)");
return "Inserted";
}
catch (Exception e)
{
return e.toString();
}
}
The below code inserts data but it opens the browser which I dont want. Also the data insertion is not always successful.
String url = "http://10.0.2.2:8080/GnPServlet/GetNpostServlet";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
conn.setRequestMethod("POST");
Looks like you're sending a POST when the servlet expects a GET (which is what the browser would send if you just paste the URL into the URL bar)
conn.setRequestMethod("GET");
...is most likely what you want since your parameters are encoded in the URL.
Also, are you sure that the spaces in your URL before account should be there?

Categories

Resources