Android开发_8:网络

本文详细介绍了在Android开发中如何使用HttpURLConnection和OkHttp进行HTTP请求,包括设置请求方法、超时时间以及读取响应数据。同时,讲解了如何解析Json格式数据,使用JsonObject和GSON库进行数据转换。通过实例展示了POST请求的发送以及Json数组的处理方法。

此博客为学习Android开发的笔记型博客,若有不妥或补充之处希望各位大神给予指正

使用HTTP协议访问网络

HttpURLConnection

1.获取URL对象

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

2.设置HTTP请求方法(GET/POST):

urlConnection.setRequestMethod("GET");

3.自由定制,诸如连接超时等时长:

urlConnection.setConnectTimeout(8000);
urlConnection.setReadTimeout(8000);

4.获取返回的输入流

InputStream in=urlConnection.getInputStream();

5.读取返回的输入流:

BufferedReader reader=new BufferedReader(new InputStreamReader(in));
StringBuilder string=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
    string.append(line);
}

6.断开连接:

urlConnection.disconnect();

使用OkHttp

1.添加依赖

dependencies {
        implementation "com.squareup.okhttp3:okhttp:4.9.0"
}

2.创建OkHttpClient

OkHttpClient client=new OkHttpClient();

3.如果想要发起HTTP请求,就要创建一个Request对象:

Request request=new Request.Builder()
.url("http://www.baidu.com")
.build();

4.获取返回的数据:

Response response=client.newCall(request).execute();

5.读取数据:

String str=response.body().string();

6.发送POST请求:

//构建RequestBody对象存放待提交的数据。
RequestBody requestBody = new FormBody.Builder().add("username","admin") 
.add("password","123456") 
.build();



//在Request.Builder()方法中调用post方法,放入RequestBody对象
Request request = new Request.Builder().urL("http://www.baidu.com")
.post( requestBody) 
.build();


//然后就和get一样了
Response response=client.newCall(request).execute();

解析Json格式数据

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 Royale"}]



JsonObject

1.先获取返回的数据流:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()// 指定访问的服务器地址是电脑本机


.urL("http://10.0.2.2/get_data.json") 


.build( );



Response response= client.newCall(request).execute(); 


String responseData = response.body().string();



2.逐个获取json对象并转化:

JSONArray jsonArray = new JSONArray(responseData); 
for(int i = 0; i<jsonArray.Length(); i++)){JSONObject jsonObject = jsonArray.getJSONObject(i); 
String id = json0bject.getString("id"); 
String name = jsonObject.getString("name"); 
String version = json0bject.getString("version"); 
Log.d("MainActivity","id is"+ id); 
Log.d("NainActivity","name is "+ name); 
Log.d("MainActivity","version is"+ version);


}

GSON

GSON库究竟是神奇在哪里呢?其实它主要就是可以将一段JSON格式的字符串自动映射成一个对象,从而不需要我们再手动去编写代码进行解析了。

json:

{"name":"tom","age":20}

1.添加依赖

compile 'com.google.code.gson:gson:2.7'

2.新建类Person:

class person{
private String name;
private int age;
}

3.直接转化:

Gson gson = new Gson();Person person = gson.fromJson(jsonData,Person.class);



4.解析Json数组:

List<Person> people = gson.fromJson(jsonData,new TypeToken<List<Person>>(){}.getType());


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值