android開發,http工具類

分類:IT技術 時間:2017-09-17

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

/* * 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();
}

}

```


Tags: 請求 String 響應 public Exception 字符串

文章來源:


ads
ads

相關文章
ads

相關文章

ad