how to set authorization header with android's httpURLconnection - android

I am attempting to connect to my server using basic authentication, but when I set the Authorization header, it causes getInputStream to throw a fileNotFound exception.
Here is the relevant code:
URL url = new URL(myurl);
//set up the connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);//this is in milliseconds
conn.setConnectTimeout(15000);//this is in milliseconds
String authHeader = getAuthHeader(userID,pass);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("authorization", authHeader);
//starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream(); //throws the fileNotFound exception
Here is the thrown exception:
java.io.FileNotFoundException: http://<myIPaddress>/login/
Weirdly enough, I have found that the fileNotFound exception is only thrown if I try to set the request property to "authorization" or "Authorization" or any variation of that word. it is not thrown if I set it to "content-type" or "authosodifjsodfjs" (a random string), as here:
conn.setRequestProperty("content-type",authHeader)//no exception thrown
conn.setRequestProperty("authosodifjsodfjs",authHeader)//no exception thrown
If I don't set this header, I am able to connect to the server with this code and get the proper access-denied message that I am expecting.
I am also able to connect to the server and login properly if I use python's "requests" module, so it is not a problem with the server.
so my question is as follows:
1) what, if anything, am I doing wrong when setting the request property as "authorization"? how do I set the auth header properly?
2) if this is a bug with HttpURLConnection, how do I file a bug report?
Thank you.
edit: it was recommended to switch from:
conn.setRequestProperty("Authorization", authHeader);
to:
conn.addRequestProperty("Authorization", authHeader);
This did not fix the problem. It is still throwing the same exception.
EDIT:
still not sure why "Authorization" and "authorization" are causing fileNotFounExceptions, but using all caps seems to work properly. here is the shiny new working code:
conn.setRequestProperty("AUTHORIZATION",authHeader);
so it looks like it needs to be all caps. "HTTP_" will be automattically added to the front of this header, so the header that the server will see is "HTTP_AUTHORIZATION", which is what it should be.

Here is part of my OAuth code which sets Authorization header:
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestProperty("User-Agent", "MyAgent");
httpUrlConnection.setConnectTimeout(30000);
httpUrlConnection.setReadTimeout(30000);
String baseAuthStr = APIKEY + ":" + APISECRET;
httpUrlConnection.addRequestProperty("Authorization", "Basic " + baseAuthStr);
httpUrlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpUrlConnection.connect();

Related

java.io.FileNotFoundException: https://api.instagram.com/v1/media/search

Why is the following code
URL url = new URL(urlStr);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
always giving me the following Exception at urlConnection.getInputStream()?
W/System.err(16253): java.io.FileNotFoundException: https://api.instagram.com/v1/media/search/access_token=1559619173.3c922fe.4fd71e26225a42a0a03fdd90ef8679a6?lat=48.858318956&lng=2.294427258&distance=500
W/System.err(16253): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
W/System.err(16253): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
W/System.err(16253): at br.com.dina.oauth.instagram.InstagramApp$5.run(InstagramApp.java:192)
You should remove urlConnection.setDoOutput(true); line because setDoOutput method force POST but instagram api work GET method.
You can also check this issue.
https://github.com/thiagolocatelli/android-instagram-oauth/issues/2
The code throwing the exception can be found for example in the okhttp github (Android uses that internally). The lines responsible are:
if (getResponseCode() >= HTTP_BAD_REQUEST) {
throw new FileNotFoundException(url.toString());
}
That simply means that the url you've provided did not result in a successful response. Throwing a *File*NotFoundException is behavior okhttp just copies from other implementations. Why someone chose this particular exception is beyond me.
If you simply put the url in the error message into a browser you'll see that you get a "Not found" page.
Explanation is simple: You're building the URL wrong. Instead of
search/access_token=...?lat=...
it needs to be
search?access_token=...&lat=...
access_token is a url parameter, not part of the path so it needs to get the ? as separator while lat becomes the second parameter which means ? needs to turn into &.

HttpURLConnection with server redirections

i'm trying to get the source code from a site using this code
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(20000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.addRequestProperty("User-Agent", "Mozilla/5.0");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
int response = conn.getResponseCode();
if (response = 307){
String locationHeader = conn.getHeaderField("Location");
URL redirectURL = new URL(locationHeader);
...
}
when the server responds with a 307 code i create a new connection with the same parameters as above with the new url given by the server.
this code works fine while following the first 2 redirects, at the third the server gives a relative url that forces a MalformedURLException when my code executes ' new URL(locationHeader); '.
so i tried to fix that adding the ' http://servername/ ' to the ' locationHeader ' string but doing that creates a loop cause the server then redirects to the first url of his redirection chain.
since my browser gets the source code from that server with no problems is there a way to achieve that with HttpURLConnection?
if someone is interested thanks to Fiddler i worked out a solution to this issue.
first i changed the "User-Agent" property to mimic the one of Mozilla then i manually tweaked the cookie the serer was sending in its reply with the relative path.
that did the trick. thank you Fiddler.

setRequestProperty throwing java.lang.IllegalStateException: Cannot set request property after connection is made

I am getting java.lang.IllegalStateException:
java.lang.IllegalStateException: Cannot set request property after connection is made error when setRequestProperty method is called after
url.openConnection();
Here is what i am trying:
URL url = new URL("https://49.205.102.182:7070/obsplatform/api/v1/mediadevices/545b801ce37e69cc");
urlConnection = (HttpsURLConnection) url
.openConnection();
urlConnection.setRequestProperty("Content-Type","application/json");
any suggestions please? Thanks in advance.
This usually happens if you have in the debug watchers calls, such as conn.getResponseCode() or anything that queries the request result before the request was actually issued or completed.
This causes, that during debug, a request is performed by the watcher, before having properly set you request, and then it becomes invalid.
I only have this issue while in debugging mode,
Run without debugging (You can print logs) everything should work fine
The obvious thing is to think that you need to add properties before calling open on the URL. this however is not the case. i have seen many samples of settings being set AFTER url has been open (as counter intuitive as that is).
the problem in my case is that i had conn.getResponseCode() added in my watch list. removed that and all good.
... tricky.
please check below code
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
I was getting the same exception on setRequestProperty("Range","byte=" + downloadedSize + "-") .
After adding connection.setChunkedStreamingMode(0); the issue disappeared
I'm having the same issue.
I was observing this issue on Nexus 5. Code of my app constantly fails with the same exception (or its twin brother "cannot set request method ..")
What I've observed that it happens if i leave phone for a while. One it starts failing it fails all the time - but if i restart phone/emulator it's ok once again).
My suspicion is its either some bug in connection pooling on framework side, or somewhere in code resources are leaked.
i found the problem it's about ordering the code, if you are trying to add header and post parameters both, it's important to be careful about this
HttpURLConnection connection = (HttpURLConnection) urlConnection;
//// Add Request Headers
for (NameValuePair nvp :
request[0].getHeaderParams()) {
connection.setRequestProperty(nvp.getName(),nvp.getValue());
}
// done
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
//// Add Post Parameters
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
List<NameValuePair> params = new ArrayList<>(request[0].getPostParams());
bufferedWriter.write(getQuery(params));
// done
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.flush();
outputStream.close();
connection.connect();
in here, i have added header parameters then set setDoInput and setDoOutput then setRequestMethod and finally you can add POST parameters.
i don't know what is wrong with setRequestMethod but i think its preparing the connection by opening it or something and that's why it throws exception
not invoke setRequestProperty after write byte to OutputStream.
OutputStream os = connection.getOutputStream();
os.write("k=v".getBytes());
os.close();
you should invoke setRequestProperty above the code
To avoid the error:
java.lang.IllegalStateException: Cannot set request property after connection is made
We have to check the connection response before access the request header fields :
URL url = new URL("https://49.205.102.182:7070/obsplatform/api/v1/mediadevices/545b801ce37e69cc");
urlConnection = (HttpsURLConnection) url
.openConnection();
//Check connection
if(urlConnection.getResponseCode() == 200/*Successful*/) {
urlConnection.setRequestProperty("Content-Type","application/json");
...
...
}

HtpsURLConnection cannot establish connection

I need to connect to server using SSL with REST. I am using HttpsURLConnection but somehow I cannot even get response code from server. The url is correct and when I try to get response code, it just throws nullPointerException.
Code snippet:
URL url = new URL("https", "xxx.com/yyy/zzz.svc", "myApi/test");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
Log.e("Response code", "Response from server: " + conn.getResponseCode());
What am I doing wrong here?
Note: I have to add remote server address and authorization token to header, but it have to return some response code anyway. For authorization error I have to receive error 400.
EDIT: The nullPointerException was hidden under Malformed URL.
Check out How to parse / read JSON data from the URL.

Android HttpURLConnection with HTTP Basic Authorization on RAILS Web Service

I'm trying around with the HttpURLConnection for quite some time now and I tried several solution posted here and on other places, but nothing seems to work.
I have the following architecture:
A Ruby on Rails Web Service (Rest interface with JSON)
An iPhone Client with RestKit
An Android Client with HttpURLConnection
The iPhone Client works like a charm. It connects to the web service with RestKit.
Now the Android Client is a completely different story. I always get a 401 Unauthorized message from the server (which results in a local FileNotFoundException).
The strange thing is, that the iPhone Client gets the same error, but RestKit somehow manages the handle it by sending the same request again. I tried that of course, but I just get the same error twice.
On the Rails Log Output it looks like this:
Started POST "/api/v1/login" for 127.0.0.1 at 2012-05-03 12:44:56 +0200
Processing by Api::V1::ApiController#session_login as JSON
Parameters: {"device"=>{"model"=>"Simulator", "system"=>"Android", "version"=>"Hugo", "name"=>"Android Simulator"}, "email"=>"florian.letz#simpliflow.com", "api"=>{"device"=>{"model"=>"Simulator", "system"=>"Android", "version"=>"Hugo", "name"=>"Android Simulator"}, "email"=>"florian.letz#simpliflow.com", "action"=>"session_login", "controller"=>"api/v1/api"}}
Filter chain halted as :require_login_from_http_basic rendered or redirected
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)
The exact same message occurs when the iPhone Client connect's but then suddenly a magical second request occurs and it goes through.
On the Android Client I do the following:
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(HTTP_POST);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
String userpassword = email + ":" + password;
con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(userpassword.getBytes())));
String body = jsonLogin.toString();
byte[] body_bytes = body.getBytes();
con.setRequestProperty("Content-Length", "" + Integer.toString(body_bytes.length));
con.setRequestProperty("Content-Language", "en-US");
con.setInstanceFollowRedirects(false);
con.setUseCaches (false);
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream ());
wr.write(body_bytes);
wr.flush ();
wr.close ();
InputStream is = con.getInputStream();
And on the last line the exception occurs.
I've read some things about redirects, but there is no redirect implemented at the server and I do not receive one on the client. I just get the 401 Unauthorized. The code in the web service and the iphone client indicate a quite simple workflow. Just send the data and receive the answer. I don't know where the SECOND login call comes from when the iPhone connects.
Does anyone here have any idea what the problem could be?
Thanks a lot!
EDIT #1:
I have identified the "magical" second request. The RestKit Log shows the following:
Asked if canAuthenticateAgainstProtectionSpace: with authenticationMethod = NSURLAuthenticationMethodDefault
This then results in the second request with quite a buch of headers I cannot make any sense of.
So do you know a way to implement this in Android?

Categories

Resources