摘要:本文主要向大家介绍了JAVA语言之http请求工具-OkHttp用法,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
本文主要向大家介绍了JAVA语言之http请求工具-OkHttp用法,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
OKHttp介绍
okhttp是一个第三方类库,用于android中请求网络。这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。
okhttp有自己的官网,官网网址:OKHttp官网如果想了解原码可以在github上下载,地址是:https://github.com/square/okhttp
在AndroidStudio中使用不需要下载jar包,直接添加依赖即可: compile ‘com.squareup.okhttp3:okhttp:3.4.1’
在开发中我们会经常需要用到http请求,这里简单介绍一个http请求工具okHttp的用法
1、导入jar包
1 <dependency>2 <groupId>com.squareup.okhttp3</groupId>3 <artifactId>okhttp</artifactId>4 <version>3.9.1</version>5 </dependency>
2、为了便于以后使用,这里封装一个OkHttpUtil的工具类
get请求
1 /**
2 * get请求
3 * @param url 请求地址
4 * @return 请求结果
5 */
6 public String doGet(String url) {
7 OkHttpClient okHttpClient = new OkHttpClient();
8 Request request = new Request.Builder().url(url).build();
9 Call call = okHttpClient.newCall(request);
10 try {
11 Response response = call.execute();
12 return response.body().string();
13 } catch (IOException e) {
14 e.printStackTrace();
15 }
16 return null;
17 }
post请求分为两种,From表单形式和JSON参数形式
·
Form表单形式
·
1 /**
2 * 表单形式post请求
3 * @param url 请求地址
4 * @param map post请求参数
5 * @return 请求结果
6 */
7 public String doPost(String url,Map<String,String> map){
8 OkHttpClient client = new OkHttpClient();
9 //构建一个formBody builder
10 FormBody.Builder builder = new FormBody.Builder();
11 //循环form表单,将表单内容添加到form builder中
12 for (Map.Entry<String,String> entry : map.entrySet()) {
13 String key = entry.getKey();
14 String value = entry.getValue();
15 builder.add(key,value);
16 }
17 //构建formBody,将其传入Request请求中
18 FormBody body = builder.build();
19 Request request = new Request.Builder().url(url).post(body).build();
20 Call call = client.newCall(request);
21 //返回请求结果
22 try {
23 Response response = call.execute();
24 return response.body().string();
25 } catch (IOException e) {
26 e.printStackTrace();
27 }
28 return null;
29 }
· JSON参数形式
1 /**
2 * Json body形式的post请求
3 * @param url 请求地址
4 * @return 请求结果
5 */
6 public String doPost(String url,String json){
7 OkHttpClient client = new OkHttpClient();
8 RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
9 Request request = new Request.Builder()
10 .post(body)
11 .url(url).
12 build();
13 Call call = client.newCall(request);
14 //返回请求结果
15 try {
16 Response response = call.execute();
17 return response.body().string();
18 } catch (IOException e) {
19 e.printStackTrace();
20 }
21 return null;
22 }
希望对JAVA有兴趣的朋友有所帮助。了解更多内容,请关注职坐标编程语言JAVA频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号