Android中進行網絡通信通常使用HttpURLConnection或HttpClient來實現,以下是一個簡單的示例代碼:
URL url = new URL("http://www.example.com/api");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// 讀取輸入流并處理數據
} finally {
urlConnection.disconnect();
}
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.example.com/api");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
// 讀取輸入流并處理數據
}
需要注意的是,Android官方推薦使用HttpURLConnection來進行網絡通信,而不推薦使用HttpClient。另外,為了避免在主線程中進行網絡請求造成ANR,建議使用AsyncTask或者開啟一個新的線程來進行網絡請求。