Issue with HttpURLConnection on Android Nexus v4.0.2 - android

The below code simply is not working on my Android Galaxy Nexus running v4.0.2 it works in the emulator and other older devices. When running on older devices and the emu the variable "is" is getting all the bytes as needed and all is good. While running on the Nexus it throws the file not found exception at "is" and "is" stays null. Then when I try to work with "is" further down the class it throws a null pointer because "is" is null. How can I fix this file not found error? The file is reachable on other devices/emu/browser.
I am getting java.io.FileNotFoundException: at is = urlConnection.getInputStream();
Here is the code:
// GET
InputStream is = null;
try {
// set the URL that points to a file to be downloaded
URL url = new URL(downloadURL);
// create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
// connect and download
urlConnection.connect();
// used in reading the data from the internet
is = urlConnection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}

urlConnection.setDoOutput(true);
Should be:
urlConnection.setDoOutput(false);

urlConnection.setDoOutput(true) effectively changes the method to POST, so probably your server doesn't respond to POST?
HTTPUrlConnection has an ugly and confusing interface indeed. Here's a recent writeup on its peculiarities:
http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection

Related

HttpURlConnection not connecting

I am making a HttpUrlConnection with an Usgs API. This is my Url:
"https://earthquake.usgs.gov/fdsnws/event/1/queryformat=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10"
After thoroughly debugging, it seems that after connection.connect connection fails and jsonResponse is empty.
public static String makeHttprequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection connection = null;
InputStream stream = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(1000000);
connection.setConnectTimeout(1500000);
connection.connect();
stream = connection.getInputStream();
jsonResponse = readfromstream(stream);
} catch (IOException e) {
Log.e("IOException", "Error while making request");
}
return jsonResponse;
}
This is Log
Everything looks good. It seems to me that you have no internet connection in your running devices. Probably you are using emulator in your computer which is not connected to internet.
Please try to run in real device. It is working perfect for me.
A bit advice, please try to use libraries such as Retrofit or OkHttp. They are very much easier and handier than these old ways.
If you insist using HttpURLConnection, try the following
URL url = new URL(yourUrlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Or for more formal use of HttpURLConnection, visit here. It shows several proper use of HttpURLConnection APIs.
https://developer.android.com/reference/java/net/HttpURLConnection
just tried my app on real device everything is working as expected there might be problem with emulator.

URL Connection close hangs sometimes

I have a function that gets the size of a file on a server. I recognize that closing the connection can take a lot of time, like 10 secs or more, sometimes.
Now I had the situation, that in the Android emulator it hanged forever, but starting the same app on a real device it went through normally.
Can someone explain this behavior or is there a better way to close the connection?
public static int getFileSizeFromURL(String sUrl) {
URL url;
URLConnection conn;
int size=0;
try {
url = new URL(sUrl);
conn = url.openConnection();
size = conn.getContentLength();
if(size < 0){
} else {
conn.getInputStream().close(); <----- hangs here in Simulator.
}
}
catch(Exception e) {
e.printStackTrace();
}
return size;
}
When size is zero then connection should be disconnect. and when size is more than zero then connection should get input stream working. Try below code.
public static int getFileSizeFromURL(String sUrl) {
URL url;
URLConnection conn;
int size=0;
try {
url = new URL(sUrl);
conn = url.openConnection();
size = conn.getContentLength();
if(size == 0){
conn.disconnect();
}
else
conn.getInputStream(); <----- hangs here in Simulator.
}
catch(Exception e) {
e.printStackTrace();
}
return size;
}
I think this might be related to your code making a GET request when you should really do a HEAD request:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
I am not sure whether this will fix the problem, but the docs say
Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance
and a GET request will definitely use more resources than a HEAD request. Unless a GET request is strictly required, you should avoid it. If you are not sure whether the server supports HEAD requests, try HEAD first and fall back to GET if the first attempt fails.

HttpURLConnection getOutputStream class cast exception on Android

I'm trying to use HttpURLConnection to send and receive messages in an Android application. This code works fine in a java application, but when running on Android I get the following exception:
java.lang.ClassCastException: com.android.okio.RealBufferedSink$1 cannot be cast to java.io.ByteArrayOutputStream
The code where this occurs:
URL url = new URL(destURI.toString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Set request properties and headers
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_LS);
con.setRequestProperty(HEADER_CONTENT_LENGTH, new Integer(wrapperBytes.length).toString());
con.setRequestMethod(METHOD_POST);
// Set connect and read timeouts
con.setConnectTimeout(timeoutInMillis);
con.setReadTimeout(timeoutInMillis);
// Write request content
ByteArrayOutputStream out = (ByteArrayOutputStream) con.getOutputStream();
out.write(wrapperBytes);
out.flush();
I've looked at the android reference pages and these seem to say what I'd expect, getOutputStream() returns an OutputStream. This should then be able to be cast to a ByteArrayOutputStream.
Where is the RealBufferedSink coming from? Why am I not getting an OutputStream back?
Any help would be greatly appreciated!
Casting
ByteArrayOutputStream out = (ByteArrayOutputStream) con.getOutputStream();
is not recommended,
you might try:
OutputStream out = new BufferedOutputStream(con.getOutputStream());

Android, not connecting to local php file

I'm trying to have my android app execute code where it opens a URL connection to a local php file that returns database entries in JSON format, but it's not connecting, after commenting out the other lines I can see that it throws an exception at the lines:
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Heres the screen shot of android code and the error log, the returned expected json file in windows and the php file:
link
Can you change your
URL url = new URL(getListUrl);
into
URL url = new URL("http://www.google.com");
and check the incoming data.
and the following is a working example.
try {
URL url = new URL("http://www.google.com");
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL Exception");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
My argument is if this code works for remote urls, it should work with localhost as well.
Hi it must be that you are using wrong local ip address in android files
it should be 10.0.2.2 not 127.0.0.1
First tell me are you testing on emulator or device
if emulator then where you define file path it should be
http://10.0.2.2/request_entries.php
just like in code
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/request_entries.php");
Managed to get the input stream using the URL:
URL url = new URL("http://10.0.2.2/request_entries.php");
result
Thanks a bunch guys :)

Android HttpURLConnection not working with cgi-bin?

I have simple code :
URL url;
BufferedReader in = null;
HttpURLConnection connection;
InputStream is = null;
InputStreamReader br = null;
setProgressTitle(progress, context.getString(R.string.loading));
setProgressMessage(progress, context.getString(R.string.loading_from_internet));
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(Const.TIMEOUT);
is = connection.getInputStream();
...
If I have urlStr = "http://samlib.ru/w/waliduda_a_a/molochnischituran1.shtml" - all is work fine.
If I use urls like urlStr = "http://samlib.ru/cgi-bin/areader?q=jlist" - I got a error in connection.getInputStream();
**
03-04 15:37:52.459: ERROR/DataReader::loadDataFromInet(17281): Failed loading http://samlib.ru/cgi-bin/areader?q=jlist
03-04 15:37:52.459: ERROR/DataReader::loadDataFromInet(17281): java.io.FileNotFoundException: http://samlib.ru/cgi-bin/areader?q=jlist
03-04 15:37:52.459: ERROR/DataReader::loadDataFromInet(17281): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
**
How can I upload data to a similar url?
There are a couple of reasons this might happen. Where I've personally seen it is when I've put in a URL that was subsequently redirected, HttpURLConnection doesn't handle that. I got the same response as you, I hit it with FF and it works fine. Its also possible that some sort of browser sniffing might be done on the recieving side.
Good Luck!
It looks like your cgi-bin/areader is not found. Getting an HTTP/404 response code:
wget http://samlib.ru/cgi-bin/areader?q=jlist
--2011-03-04 09:03:17-- http://samlib.ru/cgi-bin/areader?q=jlist
Resolving samlib.ru... 81.176.66.171
Connecting to samlib.ru|81.176.66.171|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2011-03-04 09:03:17 ERROR 404: Not Found.
Correct that then try again.

Categories

Resources