1.WebView控件
WebView可以在程序界面中嵌入浏览器页面,用于显示网页。
webView.getSettings.setJavaScriptEnabled(true);//设置WebView支持JavaScript脚本
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url); //根据传入的参数加载网页
return true; //表示使用当前WebView可以处理打开新网页的请求,不用借助系统浏览器
}
});
webView.loadUrl("http://www.jandan.net");
2.使用HTTP协议访问网络
使用HTTP协议访问一般有两种方式,HttpURLConnection和HttpClient
2.1 HttpURLConnection
//获取HttpURLConnection实例
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置HTTP请求使用的方法, GET表示希望从服务器获取数据 POST表示希望提交数据给服务器
connection.setRequestMethod("GET");
connection.setRequestMethod("POST");
//通过输出流写入,每条数据都要以键值对的形式存在,数据与数据之间用&符号隔开
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
//设置连接超时
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//获取服务器返回的输入流
InputStream in = connection.getInputStream();
// 将获取到的输入流转为字符串,便于后续处理
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
//读取完成后需要关闭此HTTP连接
connection.disconnect();
2.2 使用HttpClient
HttpClient httpClient = new DefaultHttpClient();
//发起GET请求 需创建HttpGet对象
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse response = httpClient.execute(httpGet);
//发起Post请求 需创建HttpPost对象。 通过UrlEncodedFormEntity设置提交的参数
HttpPost httpPost = new HttpPost("http://www.baidu.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "admin"));
params.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(entity);
// response 为服务器返回的数据
HttpResponse response = httpClient.execute(httpPost);
//处理服务器返回的数据 statusCode==200表示请求和响应都成功
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
}