Advertisement
Guest User

TwitterHelper.java

a guest
Jan 13th, 2015
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. import java.io.ByteArrayOutputStream;
  2. import java.io.InputStream;
  3.  
  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.StatusLine;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.impl.client.DefaultHttpClient;
  10.  
  11. import android.net.Uri;
  12.  
  13. public class TwitterHelper {
  14.  
  15. private static final String TWITTER_SEARCH =
  16. "http://search.twitter.com/search.json?q=%s";
  17. private static final int HTTP_STATUS_OK = 200;
  18. private static byte[] buff = new byte[1024];
  19.  
  20. public static class ApiException extends Exception {
  21. public ApiException (String msg)
  22. {
  23. super (msg);
  24. }
  25.  
  26. public ApiException (String msg, Throwable thr)
  27. {
  28. super (msg, thr);
  29. }
  30. }
  31. public static class ParseException extends Exception {
  32. public ParseException (String msg, Throwable thr)
  33. {
  34. super (msg, thr);
  35. }
  36. }
  37.  
  38. protected static synchronized String downloadFromServer (String keyword)
  39. throws ApiException
  40. {
  41. String url = String.format(TWITTER_SEARCH, Uri.encode(keyword));
  42. HttpClient client = new DefaultHttpClient();
  43. HttpGet request = new HttpGet(url);
  44. try {
  45. HttpResponse response = client.execute(request);
  46. StatusLine status = response.getStatusLine();
  47. if (status.getStatusCode() != HTTP_STATUS_OK)
  48. throw new ApiException("Invalid response from search.twitter.com" +
  49. status.toString());
  50. HttpEntity entity = response.getEntity();
  51. InputStream ist = entity.getContent();
  52. ByteArrayOutputStream content = new ByteArrayOutputStream();
  53. int readCount = 0;
  54. while ((readCount = ist.read(buff)) != -1)
  55. content.write(buff, 0, readCount);
  56. return new String (content.toByteArray());
  57. } catch (Exception e) {
  58. // TODO Auto-generated catch block
  59. e.printStackTrace();
  60. throw new ApiException("Problem using the API", e);
  61. }
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement