HttpURlConnection not connecting - android

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.

Related

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.

API call far faster on iOs and browser than on android

I have a trouble with my HttpsConnection on android.
First of all, no it is not a duplicate. I try almost all the solutions on SO, like changing the keep-alive option or the timeout ( and some of them indeed optimized a part of my code a little bit ) but it is still 5 to 10 times ( probably more ) slower on android than on iOS.
Sending a request to my server takes several seconds on android while it's almost instant on iOS and from a browser. I am sure that the server is not in cause. But it seems that getting the inputstream is terribly slow!
This line:
in=conn.getInputStream();
is the most delaying one, taking several seconds by itself.
My aim is to get a JSON from my server. My code is supposed to be technically as optimized as possible ( and it can probably help some people with HttpsConnection on the same time ):
protected String getContentUrl(String apiURL)
{
StringBuilder builder = new StringBuilder();
String line=null;
String result="";
HttpsURLConnection conn= null;
InputStream in= null;
try {
URL url;
// get URL content
url = new URL(apiURL);
System.setProperty("http.keepAlive", "false");
trustAllHosts();
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
conn.setRequestMethod("GET");
conn.setRequestProperty(MainActivity.API_TOKEN, MainActivity.ENCRYPTED_TOKEN);
conn.setRequestProperty("Connection", "close");
conn.setConnectTimeout(1000);
in=conn.getInputStream();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((line=br.readLine())!= null) {
builder.append(line);
}
result=builder.toString();
//System.out.print(result);
br.close();
} catch (MalformedURLException e) {
result=null;
} catch (IOException e) {
result=null;
} catch (Exception e) {
result=null;
}
finally {
try {
in.close();
}catch(Exception e){}
try {
conn.disconnect();
}catch(Exception e){}
return result;
}
}
However, it keeps taking several seconds.
So I would like to know: is there a way to improve the speed of this API call? The problem is not the server or the JSON parsing but for sure the function above. Thanks a lot.

How to improve speed of connect on Android with WIFI

URL url = new URL(URL path);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(true);
connection.connect();
InputStream is = connection.getInputStream();
Above code is my code of Android.
I try to connect an URL path and get information to InputStream is.
I try to connect the same URL path with the same wifi by Android phone and iPhone.
Android phone spend about 10 seconds by moto phones or HTC phones.
But iPhone only spend less than 3 seconds.
I think it may not only cause by wifi speed.(Because I try with the same wifi).
So I want to ask that is it possible improved by code?
Try using the apache HttpClient instead of URL.openConnection()
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("http://your.url");
HttpResponse response;
try {
response = httpClient.execute(get);
InputStream is = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
Edit:
In API level 22 (Android M) the Apache HttpClient will be removed, so this approach is deprecated.
For more infor see :
http://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client
The recommended approach is to use HttpUrlConnection (http://developer.android.com/reference/java/net/HttpURLConnection.html):
URL url = new URL("http://your.url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Use volley it is an HTTP library that makes networking for Android apps easier and faster. Volley is available on GitHub. Volley may be able to help you streamline and improve the performance of your app's network operations.

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 InputStream following a rewriterule

I'm trying to parse an xml file from a website. Let's say the website is "http://example.com"
This website has a htaccess rewrite rule setup to redirect anything with a "www" prefix to the host back to example.com. so "http://www.example.com" would redirect to "http://example.com"
In my code I have a URL that i get the InputStream of.
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
In this case feedUrl is poingting to "http://www.example.com/file.xml" and when I do the following:
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
I get an exception thrown and I believe it's not redirecting to "http://example.com/file.xml"
I could obviously just statically change where my feedUrl variable is pointing to, but I need this to be dynamic.
If anyone ran into this problem like I did, then here's the solution. The HttpURLConnection is already setup to follow redirects by default if the response code is 300, 301, 302, or 303.
For some reason, the server I'm parsing from needs to have the response code be 307 which Android does not redirect automatically.
I would suggest using a different response code, but if your server needs it then here's work around.
HttpURLConnection conn = (HttpURLConnection) feedUrl.openConnection();
int responseCode = conn.getResponseCode();
if( responseCode == 307 ){
String location = conn.getHeaderField("location");
feedUrl = new URL(location);
conn = (HttpURLConnection) this.feedUrl.openConnection();
}
Now conn can open an input stream to the correct file.

Categories

Resources