android開發,http工具類

efbb 9年前發布 | 1K 次閱讀 Java Android

android的HttpClient實現簡單的get和post請求

 
/**

  • 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 {
       while ((line = reader.readLine()) != null) {
           sb.append(line);
       }
      
      } catch (IOException e) {
       e.printStackTrace();
      
      } finally {
       try {
           is.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
      
      } return sb.toString(); } }

</pre>

 本文由用戶 efbb 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!