1 public class Http { 2 private static final int REQUEST_TIMEOUT = 5000; 3 private static final int SO_TIMEOUT = 10000; 4 5 public Http() { 6 } 7 8 public static String sendGet(String url, Map<String, String> headers) 9 throws ClientProtocolException, IOException { 10 DefaultHttpClient httpClient = (DefaultHttpClient) getHttpClient(); 11 HttpGet httpGet = new HttpGet(url); 12 String response = ""; 13 if (headers != null) { 14 httpGet.setHeaders(assembHead(headers)); 15 } 16 17 HttpResponse httpResponse = httpClient.execute(httpGet); 18 if (httpResponse.getStatusLine().getStatusCode() == 200) { 19 response = EntityUtils.toString(httpResponse.getEntity()); 20 } 21 22 httpGet.abort(); 23 return response; 24 } 25 26 public static String sendPost(String url, Map<String, String> paramsMap, 27 Map<String, String> headers) throws ClientProtocolException, 28 IOException { 29 DefaultHttpClient httpClient = (DefaultHttpClient) getHttpClient(); 30 HttpPost httpPost = new HttpPost(url); 31 String response = ""; 32 List<NameValuePair> params = new ArrayList<NameValuePair>(); 33 if (paramsMap != null) { 34 for (String str : paramsMap.keySet()) { 35 params.add(new BasicNameValuePair(str, paramsMap.get(str))); 36 } 37 } 38 httpPost.setEntity(new UrlEncodedFormEntity(params)); 39 if (headers != null) { 40 httpPost.setHeaders(assembHead(headers)); 41 } 42 43 HttpResponse httpResponse = httpClient.execute(httpPost); 44 45 if (httpResponse.getStatusLine().getStatusCode() == 200) { 46 response = EntityUtils.toString(httpResponse.getEntity()); 47 } 48 httpPost.abort(); 49 return response; 50 } 51 52 public static String assembCookies(List<Cookie> cookies) { 53 StringBuffer sb = new StringBuffer(); 54 for (Cookie cookie : cookies) { 55 sb.append(cookie.getName()).append("=").append(cookie.getValue()) 56 .append(";"); 57 } 58 return sb.toString(); 59 } 60 61 public static Header[] assembHead(Map<String, String> headers) { 62 Header[] allHeader = new BasicHeader[headers.size()]; 63 int i = 0; 64 for (String str : headers.keySet()) { 65 allHeader[i] = new BasicHeader(str, headers.get(str)); 66 i++; 67 } 68 return allHeader; 69 } 70 71 public static HttpClient getHttpClient() { 72 BasicHttpParams httpParams = new BasicHttpParams(); 73 HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT); 74 HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); 75 HttpClient client = new DefaultHttpClient(); 76 return client; 77 } 78 }