Android 5.0 OpenHttpConnection error - android

I am using eclipse and the problem is that my httpConnection code is works for android 2.3.3. but it is not working for android 5.0 I cannot handle it.
private InputStream OpenHttpConnection(String urlString) throws IOException{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if(response == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
}
catch(Exception ex){
throw new IOException ("Error connecting");
}
return in;
}
It gives me "Error connecting" on android 5.0 also android 4.0.3.

Since your describing that this error is not appearing when using android 2.3.3, it could have something to do with the new "Strict Mode".
When you're doing your network operations on the main thread, it could slow down or block the processing of the GUI which runs on the main thread. This would result in a non-responsive behaviour.
Since API level 9, there is the so called "Strict Mode", which blocks such behaviour. Therefore you have to use a AsyncTask and run your network operations on a background thread. If you don't, you usually get such errors. As mentioned in the comment above - you should get more information about the thrown exception, in order to find out what the real problem is.
See also: stackoverflow post: cannot-connect-using-httpconnection-in-android
And to read more about AsyncTask: AsyncTask

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.

HttpURLConnection getResponseCode() deos not return if there is no Internet connection

I am using a HttpURLConnection to check whether the server URL is available or not by using the following code:
try {
boolean connectionFailed = false;
URL knownURL = new URL("http://www.google.com");
httpConnection = (HttpURLConnection) knownURL.openConnection();
httpConnection.setConnectTimeout(5000);
responseCode = httpConnection.getResponseCode();
if (responseCode != 200) {
status = ConnectionStatus.NOT_CONNECTED;
}
}
catch(Exception e) {
connctionFailed = true;
}
This code is working fine under normal conditions. But when there is no Internet connection (because either the router is disconnected or not the hotspot), httpConnection.getResponseCode() is not executed (the function does not return). How can I fix this?
httpConnection.setConnectTimeout(5000)
is a timeout for connection.
This is not a timeout for httpConnection.getResponseCode().
If you add httpConnection.setReadTimeout(2000), httpConnection.getResponseCode()should throw an exception when no connection is available.
You may be having a try catch block at higher layer which is catching the sockettimeout exception.

HttpURLConnection with POST "times out" on ICS, works in HC

My Android tablet application does not work with ICS due to a Login problem. When I looked at my code and ran it under debug mode on an ICS tablet, I see the problem but I don't understand it. The code functions correctly on all Honeycomb models that i have tested and in fact I have two tablets hooked up to my computer (one Samsung Galaxy Tab running 3.2, and a Motorola Xoom wifi running 4.0.3) and the code fails on ICS and works on HC.
The failure is a Socket Timeout exception. The timeout was 2000ms, but I upped it to 100000ms to test and it had no impact.
Using the browser on the ICS tablet, I can go to the URL and it responds, so it doesn't appear to be network related.
I am running on a background thread using AsyncTask.
Slurp just takes all of the input from the InputStream and using StringBuilder creates a string representation. Its not actually useful in this request but I added it to see what the server was replying with.
I am POSTing to the page the same way a user authenticates using the form, which is why I am using x-www-form-urlencoded.
Again, this code functions perfectly on Honeycomb but fails on ICS.
The code makes a connection but fails when it asks for a response from the server, almost like the server is still waiting for something... anyway, here is the code:
static public String authenticate(String service_url, String username, String password) throws IOException {
if (username == null || password == null)
throw new IOException();
String charset = "UTF-8";
String query = String.format("Email=%s&Password=%s",URLEncoder.encode(username, charset),URLEncoder.encode(password, charset));
byte [] data = query.getBytes(charset);
URL url = new URL(service_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Length", Integer.toString(data.length));
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(5000); // 2 second timeout.
try {
connection.connect();
DataOutputStream pw = new DataOutputStream (connection.getOutputStream());
pw.writeBytes(query);
pw.flush();
pw.close();
int code = connection.getResponseCode(); //SOCKET TIMEOUT HERE
if (code == 200 || code == 302)
{
InputStream is = connection.getInputStream();
String value = slurp(is);
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
if (cookies == null)
throw new IOException();
for (String cookie : cookies) {
if (cookie.startsWith("cpms")) {
cookieTime = new DateTime(); //crazy but the expires time in the cookie is not actually accurate.
return cookie; // this is the only correct path out.
}
}
}
else
Logger.e(StaticUtils.class, "Invalid response code while logging in: " + code);
}
catch (IOException ioe)
{
Logger.e(StaticUtils.class, ioe);
throw ioe; // log it and then throw it back.
} finally {
connection.disconnect();
}
return null;
}

HttpURLConnection responsecode is randomly -1

Hi I'm using following code to establish a url connection. But randomly I get the responseCode -1 (which is the default value of responseCode):
try {
URL url = new URL(urlString);
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
handleData(new DataInputStream(httpconn.getInputStream()), requestCode);
} else {
Log.e(TAG, "HttpConnection not OK: " + httpconn.getResponseCode());
ActivityHelper.httpError(this);
}
httpconn.disconnect();
} catch (Exception e) {
Log.e(TAG, "handleHttpConnection", e);
ActivityHelper.httpError(this);
}
Am I doing something wrong? Because it works perfectly in estimated 9 of 10 attempts.
UrlConnection is buggy.
See this blog post from the official Android Developer's blog for a pre-Gingerbread workaround for one problem.
My advice, don't use it. It was still being flaky for me on 3.2. I switched to HttpClient and things have been less bad.

Android: Gzip/Http supported by default?

I am using the code shown below to get Data from our server where Gzip is turned on. Does my Code already support Gzip (maybe this is already done by android and not by my java program) or do I have to add/change smth.? How can I check that it's using Gzip? For my opionion the download is kinda slow.
private static InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
if(in == null)
throw new IOException("No data");
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
Any modern http lib support Gzip compression, it's part of a standard for ages.
But you may need to send header : "Accept-Encoding: gzip"
You can check if it's really works using sniffer in your LAN, or on the Server. You can also check response headers, but that would require code changes (most likely, you will have to turn on gzip on your webserver).
Also, you may download 10Mb file of spaces. With gzip on it would be waaaaay faster :-)
When you using HttpURLConnection class to work with HTTP protocol "Accept-Encoding: gzip" field will automatically added to outgoing requests, and will handled the corresponding response.
(see documentation)

Categories

Resources