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