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();
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().
Related
I am not familiar with https requests so please take it easy on me.
I want to make a post call and retrieve a token for a url. The url is something like:
/auth/token?param1=value1¶m2=value2¶m3=value3¶m4={{value4}}¶m5={{value5}}
I make the post
HttpURLConnection conn = (HttpURLConnection) authentication.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
but in order to get the response I have to send the parameters.
I've tried to write the url params as string to the connection outputstream but it doesnt work.
Any help is appreciated.
I am consuming API using HttpURLConnection in my android application and its running fine but if I get response code except then 200 ok (like 404, 500) my port is changing when I hit next request after error response code:
my code for android request is below and wireshark log as well:
try {
url = new URL(path_url + apiMsg); //in the real code, there is an ip and a port
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept","*/*");
}
Please refer wireshark log:
https://files.fm/u/w7umrwwk
So how to avoid PORT change in error scenario as well like in success 200 case, so that we continue to run on the same PORT.
read about sun.net.http.errorstream.enableBuffering in HttpURLConnection source code.
By default when response code is >= 400 then the connection is closed.
It is a clean though not so efficient way of handling error streams.
Instead of setting obscure system properties to handle this, it would be better to move to a proper http client like apache.
What I need to do is send POST request to specific URL with two parameters and when the request is sent, I need to redirect user to that link so that he would be able to access functionality.
So far, what I have managed to do from various examples is this:
private void postRemoteAdvisoryLink() throws IOException {
URL obj = new URL(KdrmApplicationContext.getRemoteAdvisoryUrlPath());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(60000);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// For post only - start
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(("?auth=ssor&TransportKey=" + ssorTransportKey).getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
}
The problem is that now I get connection time out when trying to execute OutputStream os = con.getOutputStream(); line. Also, I still have no idea how to redirect user when request is completed.
Any ideas?
Using the basic Java URL classes would require you to manually handle the details of HTTP protocol - it's better to use libraries like Apache Http Components, as they deal with the underlying protocols for you. Some examples including POST requests can be found on their website.
Given the original question, the Timeout is likely related to host not responding or your Java application being unable to connect to given URL (due to no proxy configuration for example).
If you want to redirect a request based on the answer, you need to check the response headers and http status - if the status is 302, then there should be a header called Location, which will contain the URL you should make another request to.
Before getting an OutputStream, also make sure to set the Content-Length header (and ideally the Content-Type header as well).
I try to send a request from an Android device to a Nodejs server using
HttpURLConnection con = (HttpURLConnection) (new URL(IP + "/getrestaurant")).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
con.getOutputStream().write("{'restaurant_id':'569a16e28dcdc5c8add2a8e0'}".getBytes("UTF-8"));
con.getOutputStream().flush();
con.getOutputStream().close();
When I print the received request from node js I get:
{
"{'restaurant_id':'569a16e28dcdc5c8add2a8e0'}": ""
}
instead of {'restaurant_id':'569a16e28dcdc5c8add2a8e0'}
How can I get it work? Thanks!
as the comment says(i have too low reputation to comment), {'restaurant_id':'569a16e28dcdc5c8add2a8e0'} is not valid context
also I advice you to use Koush Ion library for json requests . https://github.com/koush/ion
It is very convenient and easy to use for , give it a try . In one line all types of requests are done ,
The problem was that I needed con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
I am creating a django rest api, and I'm trying to send JSON data via PUT request from an Android device, using HttpUrlConnection.
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("PUT");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
Log.v("Apiput", MainActivity.cookieManager.getCookieStore().getCookies().get(0).toString());
conn.connect();
if(conn.getResponseCode() != 200) {
return "" + conn.getResponseCode();
}
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(put);
osw.flush();
osw.close();`
I know I have to send a csrf token, but I think that I'm sending it already.
By examining the META in my request I can see the csrf token both in headers and cookies:
'HTTP_COOKIE': 'csrftoken=3jLNzfLIu1P5dBH4WWwggHMH7oDQC7Rx;'
And in my android device i have a CookieManager that says that the csrf cookie has the same value.
V/Apiput﹕ csrftoken=3jLNzfLIu1P5dBH4WWwggHMH7oDQC7Rx
I am getting a 403 (Forbidden) Http error besides the user is authenticated (I can make GET Requests)
[26/Sep/2015 00:16:04]"PUT /api/works/34/ HTTP/1.1" 403 58
With curl I am able to send the request without any problem, with the same user credentials.
I wonder if anyone can tell me what am I doing wrong.
Thanks.
You don't have to set the cookie if you're doing a JSON call to Django REST framework.
It would definitively help if you can provide the permissions associated to the view.