Android网络相关

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");
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://my.oschina.net/u/2287911/blog/778869

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值