安卓学习 之 网络技术(十)

一. 显示web页面

  1. 添加布局。使用webView
  2. 添加权限<user-permission android:name = “android.permission.INTERNET”>
  3. 加载布局,webView,并作出对应的设置。
WebView webView = (WebView)findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.baidu.com");

二. 访问网络的方法

方法一:HttpURLConnection(不推荐)
URL url = new URL("https://www.qq.com/");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.connect();
InputStream in = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
StringBuffer respose = new StringBuffer();
String line ;
 while((line = reader.readLine()) != null) {
        respose.append(line);
}
showRespose(respose.toString());
方法二:OKHttp(推荐)
  1. 在 app/build.gradle 添加依赖
dependencies {
    implementation 'com.squareup.okhttp3:okhttp:3.14.1'
}
  1. 发送请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
Response response = client.newCall(request).execute();
String resposeDate = response.body().string();

三. 使用OKHttp和GSON解析JSON格式数据

  1. 准备Json格式的数据
    1)sudo apachectl start打开mac自带的apache服务器
    2)在/Library/WebServer/Documents目录下创建get_data.json文件,内容为
    [{"id":"5","version":"5.5","name":"Clash of CLans"},{"id":"6","version":"7.0","name":"Boom Beach"},{"id":"7","version":"3.5","name":"Clash Royal"}]
    3)浏览器访问localhost/get_data.json查看数据
  2. 添加GSON的依赖
dependencies {
    implementation 'com.squareup.okhttp3:okhttp:3.14.1'
    implementation 'com.google.code.gson:gson:2.8.5'
}
  1. 使用OKHttp访问网络
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
	.url("http://192.168.1.155/get_data.json")//注意不要写localhost或者127.0.0.1
	.build();
Response response = client.newCall(request).execute();
String resposeDate = response.body().string();
  1. 使用GSON解析数据
Gson gson = new Gson();
List<People> peoples = gson.fromJson(data , new TypeToken<List<People>>(){}.getType());
for(People p : peoples){
 Log.d("MainActivity","id is : "+p.getId());
Log.d("MainActivity","name is : "+p.getName());
 Log.d("MainActivity","version is : "+p.getVersion());

如果json格式不是一个数组的话

People peoples = gson.fromJson(data , People.class);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值