I am using following code for querying REST API but it is very slow. Where as response time for browser is in milliseconds. I think there is no issue in API.
Could anyone please suggest what changes I should do to optimize it? Thanks for your time
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URI);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line = "";
StringBuilder outputLine=new StringBuilder();
while ((line = rd.readLine()) != null) {
outputLine.append("\n"+line);
}
return (JSONObject)new JSONParser().parse(outputLine.toString());
I would expect the biggest delays are in the time;
it takes to get a reply
the time it takes to build a JSONObject.
You can speed up how the text is copied as follows but it might not make much difference.
HttpResponse response = client.execute(request);
char[] chars = new char[4096];
Reader rd = new InputStreamReader(response.getEntity().getContent());
StringWriter sw = new StringWriter();
for (int len; ((len = rd.read(chars)) > 0;)
sw.write(chars, 0, len);
return (JSONObject)new JSONParser().parse(sw.toString());
This is faster as it copies up to 4 KB at a time without breaking the text into lines and having to assemble it back into one block of text.
You should look in toont retrofit with okhttp. With those libraries you can easly communicate with a rest API and it also parses the body to json automatically.
Related
I've seen other StackOverflow threads, use HTTP Get to access source code of web pages. But obviously this can take a while, as this requires plentiful download time and string manipulation techniques.
I've not made use of Tripadvisor Content API before.
So an example which could possibly accomplish something similar to described below, would be incredibly helpful. Thanks
The data I would like to attain from TripAdvisor within Android is:
for a particular location (e.g. by lon and lat) e.g. Prague Bohemia etc.
A List of:
Attraction Types within that location
Ranked locations, for attraction types within that location
As shown on this page:
tripadvisor.co.uk/Attractions-g274707-Activities-Prague_Bohemia.html
Example of HTTP GET described above:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
I am running MVC 4 on my server and to save a bit of data for my users I figured I would enable GZip encoding, to do this I simply used:
(C#)
Response.AddHeader("Content-Encoding", "gzip");
Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
In my android application I use:
(Java)
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
When I use GZip the Java code nuts out and causes GC to run, I was never patient enough to wait for it to return.
When I took off GZip from the server it ran perfectly fine. The function to get the response returns straight away with no problem.
I tried adding this to the java code:
httpGet.addHeader("Accept-Encoding", "gzip");
With no success.
Question is, is there something I'm not getting? Can I not put the response in a stream if it is using GZip? Am I meant to use the stream and uncompress it after?
What am I doing wrong?
Instead of using
DefaultHttpClient client = new DefaultHttpClient();
you can use
ContentEncodingHttpClient client = new ContentEncodingHttpClient();
which is a subclass of DefaultHttpClient and supports GZIP content.
You need Apache HttpClient 4.1 for this.
If you have Apache HttpClient 4.2, you should use
DecompressingHttpClient client = new DecompressingHttpClient();
if you have Apache HttpClient 4.3, you should use the HttpClientBuilder
I have Tornado web service which returns a link after creating a CSV file as shown below.
http://10.0.2.2:8000/uploads/16165159GyjFImAYZssLEmn/16165159GyjFImAYZssLEmn.csv
Also I have outputted this URL within the Android application successfully. My question is how to parse the data of this file using the URL shown above. I have tried numerous ways and could not get it done. Can some one please help me to solve this problem. The code I have so far is as follows.
Also I have referred to this post as well, however still no success.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(modifyURL);
HttpResponse httpResponse = httpclient.execute(httpPost);
responseEntity = httpResponse.getEntity();
transformedImageURL = EntityUtils.toString(responseEntity);
URL url = new URL(transformedImageURL);
InputStream stream = url.openStream();
BufferedInputStream bis = new BufferedInputStream(stream);
ByteArrayBuffer baf = new ByteArrayBuffer(200);
nt current = 0;
while((current - bis.read()) != -1){
baf.append((byte) current);
}
String stockText = new String(baf.toByteArray());
String[] tokens = stockText.split(",");
String testData = tokens[0];
Thank you for your time
I found this great tutorial on how to use JSON to retrieve Twitter updates, and post it in a TextView:
http://www.ibm.com/developerworks/xml/library/x-andbene1/
I've followed this tutorial step by step, so my code is the same.
In the method examineJSONFile(), we have this line:
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
This file is downloaded directly from the Twitter website, as mentioned in the second paragraph of http://www.ibm.com/developerworks/xml/library/x-andbene1/#aotf.
All this is great, except for one thing: it's absolutely no use that one has to download the Twitter updates (tweets) and then build the app using this as a raw file. It should be possible to download this JSON file at runtime, and then show the tweets in the TextView afterwards.
I have tried to create the InputStream in another way, like this:
String url = "http://twitter.com/statuses/user_timeline/bbcnews.json";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuffer sb = new StringBuffer();
try
{
String line = null;
while ((line = br.readLine())!=null)
{
sb.append(line);
sb.append('\n');
}
}
catch (IOException e)
{
e.printStackTrace();
}
String jsontext = new String(sb.toString());
But it seems this line: HttpResponse response = httpclient.execute(new HttpGet(url)); throws an exception.
Any help please?
You seem to be missing the INTERNET permission. Look at the logs and it would be clear what exactly is the problem.
So, i am using this code to get the whole HTML of a website. But i dont seem to get non-ascii characters with me. all i get is diamonds with question mark.
characters like this: å, appears like this: �
I doubt its because of the charset, what could it then be?
Log.e("HTML", "henter htmlen..");
String url = "http://beep.tv2.dk";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
client.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8");
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
Header h = HeaderValueFormatter
response.addHeader(header)
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
//b = false;
html = str.toString();
Thank you. This worked (in case others have the issue):
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
client.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "iso-8859-1");
HttpGet request = new HttpGet(url);
request.setHeader("Accept-Charset", "iso-8859-1, unicode-1-1;q=0.8");
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"iso-8859-1"));
use the new InputStreamReader(in, "UTF-8") constructor
Set the Accept-Charset request header to, say, Accept-Charset: iso-8859-5, unicode-1-1;q=0.8
Make sure the page opens properly in a browser. If it does not, then it might be a server-side issue.
If none of the above works, check other headers using firebug (or similar tool)
This really helped me get started, but I was having the same problem while reading a text file. It was fixed using the following command:
BufferedReader br = new BufferedReader(new InputStreamReader(new
FileInputStream(fileName), "iso-8859-1"));
...and of course, the HTTP Response needs to have the encoding set as well:
response.setCharacterEncoding("UTF-8");
Thanks for the help!