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)
Related
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 :)
I am having trouble getting my app to open a connection to the URL that is a JSON file online. I followed guidelines how out to get the inBackground thread to fetch the URL, though when I call .connect() on that URL it seems to return out of the inBackground function because I tested just having a String that would be modified and displayed as a Toast, and modifying the String right after httpConn.connect() caused no change at all. I made sure my permissions were right in the manifest, but perhaps there is something small I am overlooking.
protected String doInBackground(URL... urls){
InputStream in = null;
String result = "test";
int responseCode = -1;
try {
URL url = urls[0];
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setRequestMethod("GET");
httpConn.setDoInput(true);
result = "get here";
httpConn.connect();
result = "don't get here";
responseCode = httpConn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
httpConn.disconnect();
result = readIt(in, 10);
return result;
}
catch (Throwable t){
t.printStackTrace();
}
return result;
}
Any ideas of what is causing there not to be any connection or how to test if I am simply overlooking or not completely understanding this? I can additional code if needed. Thank you
As I am getting ,You want to connect to a web url which returns json response .Am I right ? If yes then you need to visit this link for complete solution .
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
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.
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:)