android開發,http工具類
/**
Http工具類 */ public class HttpUtil { // 創建HttpClient對象 public static HttpClient httpClient = new DefaultHttpClient(); public static final String BASE_URL = "";
/**
- get請求
- @param url
- 發送請求的URL
- @return 服務器響應字符串
@throws Exception */ public static String doGet(String url) throws Exception { // 創建HttpGet對象。 HttpGet get = new HttpGet(url); // 發送GET請求 HttpResponse httpResponse = httpClient.execute(get); // 如果服務器成功地返回響應 if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 獲取服務器響應字符串 HttpEntity entity = httpResponse.getEntity(); InputStream content = entity.getContent(); return convertStreamToString(content);
} return null; }
/**
- post請求
- @param url
- 發送請求的URL
- @param params
- 請求參數
- @return 服務器響應字符串
@throws Exception */ public static String doPost(String url, Map<String, String> rawParams)
throws Exception {
// 創建HttpPost對象。 HttpPost post = new HttpPost(url); // 如果傳遞參數個數比較多的話可以對傳遞的參數進行封裝 List<NameValuePair> params = new ArrayList<NameValuePair>(); for (String key : rawParams.keySet()) {
// 封裝請求參數 params.add(new BasicNameValuePair(key, rawParams.get(key)));
} // 設置請求參數 post.setEntity(new UrlEncodedFormEntity(params, "utf-8")); // 發送POST請求 HttpResponse httpResponse = httpClient.execute(post); // 如果服務器成功地返回響應 if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 獲取服務器響應字符串 HttpEntity entity = httpResponse.getEntity(); InputStream content = entity.getContent(); return convertStreamToString(content);
} return null; }
/**
- 獲取服務器的響應,轉換為字符串
*/
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
} catch (IOException e) {while ((line = reader.readLine()) != null) { sb.append(line); }
} finally {e.printStackTrace();
} return sb.toString(); } }try { is.close(); } catch (IOException e) { e.printStackTrace(); }
</pre>