android http get
时间: 2023-09-24 09:10:36 浏览: 47
在 Android 中使用 HTTP GET 请求可以通过以下步骤进行:
1. 首先,你需要在你的 `AndroidManifest.xml` 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
2. 接下来,在你的 Activity 或 Fragment 中,你需要使用 Android 提供的 HttpURLConnection 类来构建 HTTP 请求。以下是一个 HTTP GET 请求的示例代码:
```java
public String httpGet(String urlStr) throws IOException {
String result = "";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为 GET
conn.setRequestMethod("GET");
// 设置连接超时和读取超时时间
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 发送请求
conn.connect();
// 读取返回数据
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// 关闭连接和流
bufferedReader.close();
inputStream.close();
conn.disconnect();
return result;
}
```
在上述代码中,我们首先创建了一个 `URL` 对象,用于指定要请求的 URL 地址。然后,我们使用 `HttpURLConnection` 的 `setRequestMethod()` 方法将请求方法设置为 `GET`。接着,我们设置了连接超时和读取超时时间,以及使用 `connect()` 方法发送请求。
然后,我们通过 `getInputStream()` 方法获取服务器返回的数据流,并使用 `BufferedReader` 对其进行读取。最后,我们关闭连接和流,并返回获取到的结果。
你可以在你的 Activity 或 Fragment 中调用此方法,例如:
```java
String result = httpGet("http://www.example.com/api/data");
Log.d("HTTP GET", result);
```
需要注意的是,在 Android 中不能在主线程中进行网络请求,因为这会导致应用程序无响应。因此,你需要在子线程中执行此操作,或使用 Android 提供的异步任务 `AsyncTask`,或使用其他第三方库来进行网络请求。