2018-03-20 OKHttp基本使用

1.添加依赖

compile 'com.squareup.okhttp3:okhttp:3.4.0'

2.创建OkHttp实例

OkHttpClient client = new OkHttpClient();

3.创建Request对象

Request request = new Request.Builder().url("").build();

4.调用execute()方法来发送请求并获取服务器返回的数据

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

5.获取返回的数据

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



若是发送一条post请求

1.创建RequestBody 对象来存放需要提交的参数

RequestBody requestBody = new FormBody.Builder().add("键名","值").build();

2.打开url连接并且传递参数

Request request = new Request.Builder().url("").post(requestBody).build();

3.调用execute()方法来发送请求并获取服务器返回的数据

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

4.获取返回的数据

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

           


解析后台传来的json数据

1.添加依赖

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

2.创建Gson对象

Gson gson = new Gson();

3.获取返回值并进行解析

List<Product> products = gson.fromJson(jsonData,newTypeTolen<List<Product>>(){}.getType());

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容