HttpURLConnection responsecode is randomly -1 - android

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.

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.

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 :)

HttpConnectionUrl always return status code 307

I am trying to hit a web service. it is working fine with android 4.4 or android 5.X. but when i am trying to hit "http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID" using android 4.1.1 it always returning me 307 status code. but this url is working fine with android 4.4 or 5.x. i also tried to hit other url it is working fine on android 4.1.1.
so please tell me what is the problem
Log.i(TAG, url);
String response = null;
HttpURLConnection conn = null;
try {
URL webServiceUrl = new URL(url);
conn = (HttpURLConnection) webServiceUrl
.openConnection();
Log.i(TAG, "Connection open");
conn.setRequestMethod(GET);
conn.setConnectTimeout(CONNECTION_TIME_OUT);
conn.setRequestProperty(CONTENT_TYPE, contentType);
conn.setRequestProperty(ACCEPT_TYPE, acceptType);
conn.setDoInput(true);
conn.connect();
Log.i(TAG, "Connection Connected");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK && conn.getInputStream() != null) {
response = StreamUtility.convertStreamToString(conn.getInputStream());
conn.getInputStream().close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
Replace your URL address with http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID/ (pay attention to / at the end). The response code will be 200.
UPDATE:
With your current URL address (http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID) without / at the end, you can use the following code:
String address = "http://inmotion-prod.cloudapp.net:145/service1.svc/json/GetCustomerUUID";
URL url = new URL(address);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(false);
// if print out (debug or logging), you will see secondURL has / at the end
URL secondURL = new URL(urlConnection.getHeaderField("Location"));
HttpURLConnection urlConnection1 = (HttpURLConnection) secondURL.openConnection();
Then use urlConnection1.getResponseCode()
Hope it helps!
BNK's answer helped, I fixed it like this so that it also works on newer devices (location header was returned as null / empty!)
String headerLocation = httpsUrlConnection.getHeaderField("Location");
logger.debug("Location header: " + headerLocation);
// if the redirect URL ends with a "/" sign, but the original URL does not, it's probably the redirect bug
String originalURL = url.toString();
if (!TextUtils.isEmpty(headerLocation) && headerLocation.endsWith("/") && !originalURL.endsWith("/"))
{
logger.info("Redirect Location differs from original URL, create new connection to: " + headerLocation);
httpsUrlConnection = (HttpsURLConnection) new URL(headerLocation).openConnection();
// optional
httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
}

What is the difference between httpconnection on J2ME and HttpUrlConnection on Android (http error 401)

I connect to two servers (PROD is https, test server is http) on my applicaitons.
on J2ME: I can connect to this two servers without a problem.
on Android I can't connect to test-server. When connection is http, if I dont use setChunkedStreamingMode, I cant get responseCode(StringIndexOutOfBoundsException); if I use setChunkedStreamingMode, response code is 401. What should I do, where is my fault??
Here is my android code, Also if you want to see J2me code, I can add it, too.
URL url = new URL(getUrl());
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setConnectTimeout(10000);
httpConn.setRequestProperty("User-Agent", util.getDeviceFullModel()
+ " " + util.getSoftwareVersion());
httpConn.setRequestProperty("Accept-Charset", "utf-8");
httpConn.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction",
"http://tempuri.org/IAuthenticationServiceForGroup/"+conTypeString);
httpConn.setRequestProperty("Software-Version", AppData.VERSION);
httpConn.setChunkedStreamingMode(getParams().getBytes("UTF8").length);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.connect();
os = httpConn.getOutputStream();
os.write(getParams().getBytes("UTF8"));
try {
os.close();
} catch (Exception e) {
onError(e);
}
response=httpConn.getResponseCode();
J2ME code:
HttpConnection c = (HttpConnection)XConnection.openConnection(XConnection.SERVER + "AuthenticationServiceForGroup.svc");
c.setRequestProperty("User-Agent", XUtil.getDeviceFullModel() + " " + XUtil.getSoftwareVersion());
c.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
c.setRequestProperty("SOAPAction", "http://tempuri.org/IAuthenticationServiceForGroup/"+conType);
c.setRequestProperty("Software-Version", XApp.VERSION);
c.setRequestMethod(HttpConnection.POST);
OutputStream os = null;
os = c.openOutputStream();
os.write(sParams.getBytes());
try {os.close();} catch (Exception e) {}
if (c.getResponseCode() == HttpConnection.HTTP_OK)
If you're using pre-2.3 devices, HTTPUrlConnection has known issues
http://android-developers.blogspot.com/2011/09/androids-http-clients.html
I solved this problem. I use ip adress instead of link. Server was Sharepoint server so, It tries to connect to directly sharepoint server, so server wants Authentication:) Dont use directly ip:)

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