actually i have a correct code that makes a http petition to twitter and get's some tweets from a user codified with JSON (it gets a file .json)
It's ok, it works fine, but it takes a loooooooooooooot of time making the request, debugging i can see that the problem is on the line HttpResponse response = httpclient.execute(httpget);
On that line it gets stuck a lot of seconds when the number of tweets is more than 3 or 4 tweets. If you are requesting 20 tweets it takes 10-15 seconds to get them.
It is a problem of the java/android http get method i am using, because if i make the request by url on firefox, then, it is super fast.
How to make this http get request by a faster way?
This is my actual and slow code:
public List<String> RetrieveTweets(String name, int num) //da todas las posiciones dado un email
{
// https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=charliesheen&count=2
List<String> tweetsList= new ArrayList<String>();
开发者_JS百科 String result = "";
//http get
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=" + name +"&count="+ num);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
tweetsList.add(json_data.getString("text")); //text es el nombre del campo del tweet
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return tweetsList;
}
Are you required to use https version to get the statuses? Https will be slower than http because of two things:
- Initial connect requires a handshake negotiation for deciding cipter algorithm + session key
- Once the handshake is established, each way of communication requires encryption/decryption of the message.
If you are required to us SSL, you could try instantiating the HttpClient once and not instantiating every time in the method. Hopefully, it will keep the session alive and thus avoiding the handshake which can be costly if you initiate it every time.
精彩评论