在Android中,可以使用HttpClient或者HttpURLConnection來調用API接口。
使用HttpClient調用API接口的步驟如下:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", value1));
params.add(new BasicNameValuePair("param2", value2));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpClient.execute(httpGet); // 或者httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
使用HttpURLConnection調用API接口的步驟如下:
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // 或者"POST"
String params = "param1=value1¶m2=value2";
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(params);
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
InputStream inputStream;
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder responseString = new StringBuilder();
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
reader.close();
以上是簡單的調用API接口的示例,實際使用中可能需要根據具體情況進行適當的修改和處理。另外,記得在AndroidManifest.xml文件中添加網絡權限:
<uses-permission android:name="android.permission.INTERNET" />