Android的网络技术(1) - 通过WebView控件和HTTP协议访问网络

来源:互联网 发布:datestatus js 编辑:程序博客网 时间:2024/05/16 06:14

WebView控件

我们可以在不调用浏览器的情况下,使用WebView控件来来在显示网页,相当于在Android应用中嵌入一个浏览器。


使用方法并不难,首先要在布局中添加一个WebView控件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <WebView        android:id="@+id/web_view"        android:layout_width="match_parent"        android:layout_height="match_parent" /></LinearLayout>


然后在活动中修改代码:

public class MainActivity extends Activity {private WebView webView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);webView = (WebView) findViewById(R.id.web_view);webView.getSettings().setJavaScriptEnabled(true);webView.setWebViewClient(new WebViewClient() {@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {// 根据传入的参数再去加载新的网页view.loadUrl(url);// 表示当前WebView可以处理打开新网页的请求,不用借助系统浏览器return true;}});webView.loadUrl("http://www.google.com.hk");}}


然后我们还需要添加访问网络的权限。

<uses-permission android:name="android.permission.INTERNET" />


运行这个应用之后就可以得到Google的首页。



使用HTTP协议访问网络

HTTP的工作原理其实很简单,是客户端向服务器发出一条HTTP请求,服务器收到请求之后返回一些数据给客户端,然后客户端再对这些数据进行解析和处理就可以了。刚刚的WebView控件实际上就是实现了这个流程。在Android上发送HTTP请求的方式一般有两种,HttpURLConnection和HttpClient。

使用HttpURLConnection

首先需要获取一个HttpURLConnection的实例,一般可以通过一个URL对象的openConnection方法获取到。
URL url = new URL("http://www.baidu.com");HttpURLConnection connection = (HttpURLConnection) url.openConnection();


接下来可以设置HTTP请求所使用的方法,常用的方法主要有GET和POST两个。GET表示希望从服务器那里获取数据,POST表示希望提交数据给服务器。写法如下:
connection.disconnect();

接下来可以进行一些自由的定制,参见HttpURLConnection的API或HttpURLConnection用法详解。

之后再调用getInputStream方法可以获取到服务器返回的输出流,再之后就可以对输入流进行读取。

最后可以调用disconnect方法将这个HTTP连接关闭掉。
connection.disconnect();

若是想使用POST方法,例如如下即可,注意数据间要以&分隔:
connection.setRequestMethod("POST");DataOutputStream out = new DataOutputStream(connection.getOutputStream());out.writeBytes("username=admin&password=123456");


使用HttpClient

HttpClient是Apache提供的HTTP网络访问接口,几乎可以和HttpURLConnection完成一样的效果。

首先,因为HttpClient是一个接口,所以我们并不能创建它的实例。通常情况下会创建一个DefaultHttpClient的实例。
HttpClient httpClient = new DefaultHttpClient();

接下来如果想要发起一个GET请求,可以创建一个HttpGet对象,并传入目标的网络地址,然后调用HttpClient的execute方法即可。
HttpGet httpGet = new HttpGet("http://www.google.com.hk");httpClient.execute(httpGet);

发送POST请求需要先创建一个HttpPost对象,并传入目标的网络地址。然后通过一个NameValuePair集合来存放要提交的参数,然后将这个集合传入到一个UrlEncodedFormEntity中,然后调用HttpHost的setEntity方法调入刚才的UrlEncodedFormEntity即可。
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);

接下来也是使用一个execute方法即可。
1 0
原创粉丝点击