文章目录
- 一、环境说明
-
-
- 1、在gradle中引入依赖
- 2、AndroidManifest中开启网络权限
- 3、搭建测试接口
- 4、编写OkHttp工具类
-
- 二、发送请求
-
-
- 1.发送无参的Get请求
- 2.发送有参的Get请求
- 3.发送无参Post请求
- 4.发送有参Pos请求
- 5.发送Post 的Json数据
-
一、环境说明
1、在gradle中引入依赖
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
2、AndroidManifest中开启网络权限
<uses-permission android:name="android.permission.INTERNET"/>
注意:
在android9.0以后,Android默认禁止使用Http协议,必须使用Https协议,否则会报错误。
所以要使用Http协议的请求必须在AndroidManifest中添加属性,android:usesCleartextTraffic=“true”
3、搭建测试接口
package com.icodingzy.androidback.controller;
import com.icodingzy.androidback.pojo.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("getUser")
public Object getUser() {
User user = new User();
user.setId((int) (Math.random()*100));
user.setName("熊顺");
user.setStudentId("201815110110" + (int) (Math.random()*100));
user.setSex("男");
user.setData("Not have Parameter!");
return user;
}
@GetMapping("getParamUser")
public Object getParamUser(Integer id){
User user = new User();
user.setId(id);
user.setName("熊顺");
user.setStudentId("201815110110" + (int) (Math.random()*100));
user.setSex("男");
user.setData("parameter is " + id);
return user;
}
@PostMapping("postNoParamUser")
public Object postNoParamUser(){
User user = new User();
user.setId((int) (Math.random()*100));
user.setName("熊顺");
user.setStudentId("201815110110" + (int) (Math.random()*100));
user.setSex("男");
user.setData("Not have parameter");
return user;
}
@PostMapping("postParamUser")
public Object postParamUser(Integer id){
User user = new User();
user.setId(id);
user.setName("熊顺");
user.setStudentId("201815110110" + (int) (Math.random()*100));
user.setSex("男");
user.setData("parameter is " + id);
return user;
}
@PostMapping("postObjectParamUser")
public Object postObjectParamUser(@RequestBody User user){
return user;
}
}
接口文档
说明 | 请求方式 | 请求参数 | 请求地址 |
---|---|---|---|
GET 方式,无参数 | GET | 无 | /user/getUser |
GET方式,Int参数 | GET | Int(id) | /user/getParamUser |
Post方式,无参数 | POST | 无 | /user/postNoParamUser |
Post方式,有参数 | POST | Int(id) | /user/postParamUser |
Post方式,Json化参数 | POST | Object(id,name,sex,studentId,sex,data) | /user/postObjectParamUser |
4、编写OkHttp工具类
package com.zhuoyue.travelwh.OkHttpUtil;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import com.zhuoyue.travelwh.bean.MsgBean;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttpUtil {
public static ProgressDialog dialog;
public static void getHttpRequset(String url, Context context, RequestBody body) {
startDialog(context);
OkHttpClient client = new OkHttpClient();
Request request = null;
//Post请求
if (body != null) {
request = new Request.Builder()
.url(url)
.post(body)
.build();
} else {
//Get请求
request = new Request.Builder()
.url(url)
.get()
.build();
}
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
stopDialog();
Log.e("onFailure: ", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
stopDialog();
Log.e("ApiData:", response.body().string());
}
});
}
public static void startDialog(Context context) {
dialog = new ProgressDialog(context);
dialog.setMessage("数据加载。。。");
dialog.setTitle("请稍后");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
public static void stopDialog() {
if (dialog != null) {
dialog.dismiss();
}
}
}
二、发送请求
1.发送无参的Get请求
在自己的业务中使用工具类发送网络请求
//无参接口
private final String url = "http://xxxxxx/user/getParamUser";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OkHttpUtil.getHttpRequset(url,this,null);
}
打印结果如下
E/ApiData:: {“id”:82,“name”:“熊顺”,“studentId”:“20181511011066”,“sex”:“男”,“data”:“Not have Parameter!”}
2.发送有参的Get请求
OkHttp发送Get请求时,请求参数全部放在url中
//有参Get接口
private final String url = "http://xxxxxx/user/getParamUser";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OkHttpUtil.getHttpRequset(url + "?id=9999",this,null);
}
3.发送无参Post请求
发送Post请求时必需要带上请求体
//无参Post接口
private final String url = "http://xxxxxx/user/postNoParamUser";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestBody body = new FormBody.Builder()
.build();
OkHttpUtil.getHttpRequset(url, this, body);
}
4.发送有参Pos请求
add中固定为String类型
//有参Post接口
private final String url = "http://xxxxxx/user/postParamUser";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestBody body = new FormBody.Builder()
.add("id","8888")
.build();
OkHttpUtil.getHttpRequset(url, this, body);
}
5.发送Post 的Json数据
发送Json数据需要借助JSONObject,把数据转换成Json格式
//Json化参数Post接口
private final String url = "http://xxxxxx/user/postObjectParamUser";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("id",1111111);
jsonObject.put("name","顺");
jsonObject.put("studentId","123123");
jsonObject.put("sex","小萌新");
jsonObject.put("data","I have pan");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = FormBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString());
OkHttpUtil.getHttpRequset(url, this, body);
}