/WhereAbout/src/com/google/marvin/whereabout/HttpUtil.java

http://eyes-free.googlecode.com/ · Java · 54 lines · 34 code · 7 blank · 13 comment · 4 complexity · e4b6dd3af277a4f43ca66dad2da261ac MD5 · raw file

  1. package com.google.marvin.whereabout;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import android.util.Log;
  9. public class HttpUtil {
  10. private static final String ENCODING = "UTF-8";
  11. /**
  12. * Sends a request to the specified URL and obtains the result from
  13. * the sever.
  14. * @param url The URL to connect to
  15. * @return the server response
  16. * @throws IOException
  17. */
  18. public static String getResult(URL url) throws IOException {
  19. return toString(getResultInputStream(url));
  20. }
  21. public static InputStream getResultInputStream(URL url) throws IOException {
  22. Log.d("Locator", url.toString());
  23. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  24. Log.d("Locator", "After open connection");
  25. conn.setDoInput(true);
  26. conn.setDoOutput(true);
  27. return conn.getInputStream();
  28. }
  29. /**
  30. * Reads an InputStream and returns its contents as a String.
  31. * @param inputStream The InputStream to read from.
  32. * @return The contents of the InputStream as a String.
  33. * @throws Exception
  34. */
  35. private static String toString(InputStream inputStream) throws IOException {
  36. StringBuilder outputBuilder = new StringBuilder();
  37. String string;
  38. if (inputStream != null) {
  39. BufferedReader reader =
  40. new BufferedReader(new InputStreamReader(inputStream, ENCODING));
  41. while (null != (string = reader.readLine())) {
  42. outputBuilder.append(string).append('\n');
  43. }
  44. }
  45. return outputBuilder.toString();
  46. }
  47. }