安卓开发获取网页源码
时间: 2023-10-04 21:12:13 浏览: 20
在安卓开发中,可以使用 HttpURLConnection 或者 OkHttp 等网络库来获取网页源码。以下是使用 HttpURLConnection 的示例代码:
```java
public String getWebPageSource(String url) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL u = new URL(url);
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该方法会返回指定网页的源码字符串。