《第一行代码》学习笔记之网络技术
《第一行代码》学习笔记之网络技术
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");
权限声明:
<uses-permission android:name="android.permission.INTERNET"/>
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");
}