安卓开发-网络与通信

1、WebView

  WebView是一个使用WebKit引擎的浏览器控件,因此,可以将WebView当成一个完整的浏览器使用。

  WebView webView = ( WebView )findViewById(R.id.webview);

  webView.loadUrl( "https://www.baidu.com");

  WebView也可以浏览本地的网页文件或任何WebView支持的文件。

  webView.loadUrl( "file:///sdcard/images.jpg");

webView.goBack();                //向后浏览历史页面
webView.goForward();            //向前浏览历史页面
WebView.clearCache();            //清除缓存内容

2、HTTP

  Android SDK 中可以采用多种方式使用HTTP,例如HttpURLConnection、HttpGet、HttpPost等。

  2.1HttpGet、HttpPost

  无论是使用HttpGet,还是HttpPost,都必须通过如下3步来访问HTTP资源。

  (1)创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

  (2)使用DefaultHttpClient.execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。

  (3)通过HttpResponse.getEntity方法返回响应信息,并进行相应的处理。

HTTP GET:
    url
+= "?bookname=" + etBookName.getText().toString();     HttpGet httpGet = new HttpGet( url );     httpResponse = new DefaultHttpClient().execute( httpGet ); HTTP POST: HttpPost httpPost = new HttpPost( url ); //设置HTTP POST请求参数必须用NameValuePair对象 List< NameValuePair > params = new ArrayList< NameValuepair >(); params.add( new BasicNameValuePair( "bookname ", etBookName.getText().toString() ) ); //设置HTTP POST请求参数 httpPost.setEntity( new UrlEncodedFormEntity(params, HTTP.UTF_8)); //使用execute方法发送请求 httpRespinse = new DefaultHttpClient().execute( httpPost );

   2.2HttpURLConnection

    URL url = new URL( "http://www.xxxx.html");

    HttpURLConnection httpURLConnection = ( HttpURLConnection ) url.openConnection();

    httpURLConnection.setRequestMethod( "POST" ); 

 

 

posted @ 2015-03-30 23:32  Mr_Right  阅读(243)  评论(0编辑  收藏  举报