《第一行代码》学习笔记之网络技术

《第一行代码》学习笔记之网络技术

1.WebView控件使用:

xml:

<WebView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/web_view">
</WebView>

代码:

 private WebView webView;
 webView = (WebView) findViewById(R.id.web_view);
 //设置webView属性能够执行JavaScript
 webView.getSettings().setJavaScriptEnabled(true);       
 webView.setWebViewClient(new WebViewClient(){
      @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
     view.loadUrl(url);
   }
});
   webView.loadUrl("http://www.baidu.com");

 ```

权限声明:


2.HttpURLConnection

Android发送HTTP请求的方式一般有两种:**HttpURLConnection**和**HttpClient**

- #### HttpURLConnection用法:

new 出一个URL对象,并传入目标的网络地址,然后调用openConnection()方法:

URL url = new URL(“http://www.baidu.com“);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();

设置HTTP请求所使用的方法,GET或POST:

connection.setRequestMethod(“GET”);

““

设置连接超时、读取超时的毫秒数

 connection.setConnectTimeout(8000);
 connection.setReadTimeout(8000);

获取服务器返回的输入流:

  InputStream in = connection.getInputStream();

关闭HTTP连接:

connection.disconnect();
  • #### HttpClient用法:

HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例:

    HttpClient httpClient = new DefaultHttpClient();

发起一条DET请求,传入目标的网络地址,调用HttpClient的execute()方法:

HttpGet  httpGet = new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);

发起一条Post请求,传入目标的网络地址,通过NameValuePair集合来存放待提交的参数,将集合参数传入到UrlEncodedFormEntity中,调用httpPost的setEntity()方法:

 HttpPost httpPost = new HttpPost("http://www.baidu.com");
 List<NameValuePair> params = new ArrayList<NameValuePair>();
 params.add(new BasicNameValuePair(键值对));
 UrlEncodedFormEntity entity = null;
 entity = new UrlEncodedFormEntity(params,"utf-8");
 httpPost.setEntity(entity);
 httpClient.execute(httpGet);

服务器返回的所有信息包含在HttpResponse对象,取出服务器返回的状态码,调用getEntity()方法获取到一个HttpEntity实例,在转换成字符串:

 HttpResponse httpRespons=httpClient.execute(httpPost); 
 if(httpResponse.getStatusLine().getStatusCode()==200){
         HttpEntity entity = httpResponse.getEntity();
         String response = EntityUtils.toString(entity,"utf-8");      
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值