I had developed an application in which I hit several URLs and show data on mobile. But the problem is that it requires more time. If I check the same URL on Firebug tool I get a response in 2-3 seconds, but the same URL requires 8-15 seconds on mobile. In my Android application I am using HTTP get and post method as follows:
public InputStream httpGetResponseStream(String url, String request) {
connectionUrl = url;
InputStream response = null;
try {
processGetRequest();
HttpResponse httpresponse = httpclient.execute(host, get);
response = httpresponse.getEntity().getContent();
} catch (Exception e) {
response = null;
}
return response;
}
public InputStream httpPostResponseStream(String url, String request) {
connectionUrl = url;
InputStream response = null;
try {
processPostRequest();
if (request != null) {
InputStreamEntity streamEntity = new InputStreamEntity(
new ByteArrayInputStream(request.getBytes()), request
.length());
post.setEntity(streamEntity);
}
HttpResponse httpresponse = httpclient.execute(host, post);
response = httpresponse.getEntity().getContent();
}catch (Exception e) {
response = null;
}
return response;
}
private void processGetRequest(){
uri = Uri.parse(connectionUrl);
String protocol = connectionUrl.substring(0, 5).toLowerCase();
if (protocol.startsWith("https")) {
securedConnection = true;
} else {
securedConnection = false;
}
if (securedConnection) {
host = new HttpHost(uri.getHost(), 443, uri.getScheme());
} else {
host = new HttpHost(uri.getHost(), 80, uri.getScheme());
}
get = new HttpGet(uri.getPath()+query_string);
}
private void processPostRequest() {
uri = Uri.parse(connectionUrl);
String protocol = connectionUrl.substring(0, 5).toLowerCase();
if (protocol.startsWith("https")) {
securedConnection = true;
} else {
securedConnection = false;
}
if (securedConnection) {
host = new HttpHost(uri.getHost(), 443, uri.getScheme());
} else {
host = new HttpHost(uri.getHost(), 80, uri.getScheme());
}
post = new HttpPost(uri.getPath());
}
Any suggestion to improve code will be appreciated
HttpUrlConnection
instead ofHttpClient
. Android's HTTP clients – vasart Mar 1 '13 at 12:01