Android HttpURLConnection content length - android

I am trying to download files from a server in android and show progress dialog using code very similar to the answer provided in this thread but i am not able to get content length in HttpURLConnection's getContentLength() method. Content length for all files is -1.
For the same file, i get correct content length in iOS app with NSHTTPURLResponse's expectedContentLength method.
Is there some basic difference in the way these methods fetch the content length for an http connection/response?
EDIT 1:
Tried following few things as suggested some answers and comments.
Set Accept-Encoding header to identity
Fetching the content length as string (from header field Content-Length) and then converting it to long
Tried conn.getContent().toString().length() instead of getContentLength()
None of these worked for me yet.
What baffles me most is i get the content length in iOS but not on android.
EDIT 2:
Heres my iOS and Android code for comparison -
iOS:
NSURLRequest *request = [NSURLRequest requestWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
Android:
URL url = new URL(downloadUrlString);
connection = (HttpURLConnection) url.openConnection();
connection .setRequestProperty("Accept-Encoding", "identity");
connection.connect();
The only difference i can see is caching.
So i added following line in android code as well but nothing changed.
connection.setUseCaches(true);

try this:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn .setRequestProperty("Accept-Encoding", "identity");
conn.connect();

if you just need to content length, can you try
conn.getContent().toString().length()
where conn is the HttpURLConnection object

Root cause for this problem turned out to be Cookies.
I am using a web view in one of the activities in my application. Some cookies are stored by the web view. All other REST api and file download requests work without those cookies however for a particular type of requests, the cookies are necessary.
Apparently, android web view and the connection requests do not share cookies out of the box like iOS. As a result i had to make changes in my code to make sure that the HttpUrlConnection uses WebKit's cookie store. I did it using method described in the accepted answer for this question.

Related

Why Instagram GET request return "405 Method not allowed"?

I can easily GET data through the following request:
https://api.instagram.com/v1/tags/nofilter/media/recent?access_token=my_access_token
using my web browser. And all data is correct.
But when I trying to request using Android
URL url = new URL(urlStr);
cn = (HttpsURLConnection) url.openConnection();
cn.setDoInput(true);
cn.setDoOutput(true);
cn.setRequestProperty("access_token", my_access_token );
cn.setRequestMethod("GET");
cn.connect();
I getting "405 Method not allowed" response. Why? How to access Instagram API through the Android.
Also I want to note that access token is getting well in same manner but with method POST and some output message (as described in manual), so I am sure that my_access_token is correct and up to date.
Best Regards
Ekaterina

Searching for code to log raw HTTP+cookies from Android HttpURLConnection

Has anyone released code to show the full HTTP request/response headers, any intermediate redirects, and any cookie data for the Android HttpURLConnection? This would be similar to Firefox Web Console
I roughly know how to write this myself, but 1) it's a non-trivial amount of code 2) it's tricky to get this kind of code to work in all instances. So i'm interested in finding a readymade solution. I know how to tcpdump the emulator, but I'm searching for code to print this information into the Android Log class for really quick runtime debugging.
for header fields
URL url = new URL(str_url);
HttpURLConnection conection = (HttpURLConnection) url.openConnection();
conection.setConnectTimeout(TIMEOUT_SOCKET);
conection.setReadTimeout(TIMEOUT_CONNECTION);
conection.addRequestProperty("Accept-Encoding", "gzip");
RedirectLocations locations = new RedirectLocations();
// here u get all header fields and properties write it in logs
conection.getHeaderFields();
conection.getRequestProperties();
// conection.getOutputStream().write(buffer);
// download the file
InputStream is = conection.getInputStream();
// This is file path were a; quiz data will get saved.
// String file_path = context.getDir(folder,Activity.MODE_PRIVATE).getAbsolutePath();
return unzip(is,save_file_path);
for redirects
link
after u get response, again u ve to look for header fields

getInputStream() method is returning an empty String in Android

I am trying to develop an application where I can get the HTML source of any web page. I am able to get the code but when I am trying the same code using some facebook profile links, it gives me an empty string.
I am using HttpURLConnection. I am trying the code as follows:
URL url = new URL(urlPassed);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
and I am trying to read that buffer in a loop as buffer.read(by) where "by" is a byte array of size 7024. However, it works fine for all other web pages except facebook pages.
Any reason for this? Any idea to solve this?

Android - Header content-length equal -1

I'm downloading a file in my android app and I want to display a progressbar. I need to know the total file size by using this method : here.
The problem is that I always get -1 despite the fact that it's set on the server and I can see it from my computer.
This is the code :
URL url = new URL(fileUrl);
URLConnection ucon = url.openConnection();
ucon.connect();
int length = ucon.getContentLength();
What is the problem ?
This is not related to Android, most probably it was not sent from the server..please use any sniffing tool to make sure the content length header is there.

How can I use http auth information from a URL in Android?

In my browser, or in iOS, when I try to get the contents of a URL with encoded http authentication information in the form
http://myUser:myPassword#www.example.com/secure/area/index.html
It just works. I'm getting URLs from a web service, and I'd like to avoid trying to parse them up for their HTTP auth info if I can help it. Is there a way to do something similar in Android without actually parsing the URLs? Alternatively, what is the best way to go about that?
UPDATE:
I find that when I try to set the authentication information in an Authorization header, I get a very strange FileNotFoundException.
Here's the code I'm using:
URL url = new URL(urlString);
URLConnection connection;
String authority = url.getAuthority();
if (authority.contains("#")) {
String userPasswordString = authority.split("#")[0];
url = new URL(urlString.replace(userPasswordString + "#", ""));
connection = url.openConnection();
String encoded = new String(Base64.encode(userPasswordString.getBytes(), Base64.DEFAULT), "UTF-8");
connection.setRequestProperty("Authorization", "Basic " + encoded);
} else {
connection = url.openConnection();
}
InputStream responseStream = connection.getInputStream();
All the info seems to check out, I've verified the url is correct, the base64 string is correct, and the file is certainly on the server--I have no trouble at all opening it with Firefox, and Firebug shows all the right headers, matching what I've sent as far as I can tell. What I get though is the following error (url host changed to protect the innocent):
java.io.FileNotFoundException: http://a1b.example.com/grid/uploads/profile/avatar/user1/custom-avatar.jpg
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
Any idea what this is all about?
I looked into using HttpClient, but saw that in Issue 16041 it is recommended that we prefer URLConnection.
That looks like your browser is applying some extra rules to parsing the URL. In Android you can use HTTP Client's authentication mechanism such as BASIC and DIGEST to do the same things. Which one you choose is dependent on the server you are trying to authenticate against.
Here is a good page to get you started.
Unfortunately, on Android you can't pass the user info (username/password) in that format to either java.net.URL or HttpClient and have it work like in a browser.
I'd recommend using URI (see http://download.oracle.com/javase/1.5.0/docs/api/index.html?java/net/URI.html) to do this: pass your URL to the URI constructor that takes a String and then you can extract the user info (using getUserInfo()). You can then either use HttpClient's authorization classes (see http://developer.android.com/reference/org/apache/http/auth/package-summary.html) or build the basic auth header yourself (an example is given at http://www.avajava.com/tutorials/lessons/how-do-i-connect-to-a-url-using-basic-authentication.html).

Categories

Resources