Home HttpUrlConnection Post with header info but no body
Reply: 1

HttpUrlConnection Post with header info but no body

Smiley
1#
Smiley Published in 2017-11-14 22:00:04Z

I am developing an Android app that uses an API I developed.

I am doing this connection using HttpUrlConnection and so far the login works fine. The problem arises with the logout. It´s not doing anything. When I do the logout request with Postman then it works fine, but with HttpUrlConnection it does not.

The logout works like this: Do a POST request to http://ipaddress:12345/api/LogOut

and in the header include the token of the logged user. Then the server should go to the database and delete the token for that user:

This is how I´m trying to do the request:

URL url = new URL(getString(R.string.url) + "LogOut");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Token", TokenSingleton.getToken());

con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.connect();
con.getOutputStream().flush();
con.getOutputStream().close();
con.disconnect();
EJP
2#
EJP Reply to 2017-11-14 22:11:44Z

Nothing happens until you do some input. At least call getResponseCode() to see whether you got a 200 or not. Preferably you should consume the input stream, if 200 <= response code <= 299, otherwise the error stream.

NB setDoOutput(true) sets the request method to POST. You don't need to do that yourself. And setDoInput(true) is the default. And close() implies flush().

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.342136 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO