怎么使用安卓原声api获取接口
时间: 2024-09-15 18:14:21 浏览: 63
在Android应用程序中,如果你想要使用原生API来获取网络接口的数据,通常会通过HttpURLConnection、OkHttp或者Retrofit库来实现。以下是使用HttpURLConnection的一个简单示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ApiService {
private static final String BASE_URL = "https://api.example.com/data";
public void fetchDataFromApi(String endpoint, Callback callback) throws Exception {
URL url = new URL(BASE_URL + endpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方式(GET, POST等)
connection.setRequestMethod("GET");
// 设置超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
callback.onSuccess(response.toString());
} else {
callback.onError("Error: " + responseCode);
}
connection.disconnect();
}
interface Callback {
void onSuccess(String data);
void onError(String error);
}
}
```
在这个例子中,`ApiService`是一个封装了网络请求的服务,它有一个回调接口`Callback`,当请求成功或失败时,会调用对应的回调方法传递数据或错误信息。
阅读全文