Article Directory
1. Environmental description
1. Introduce dependencies in gradle
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
2. Turn on network permissions in AndroidManifest
<uses-permission android:name="android.permission.INTERNET"/>
note:
After android9.0, Android prohibits the use of Http protocol by default, and Https protocol must be used, otherwise an error will be reported.
So the request to use the Http protocol must add attributes in AndroidManifest, android:usesCleartextTraffic="true"
3. Build a test interface
package com.icodingzy.androidback.controller;
import com.icodingzy.androidback.pojo.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("user")
public class UserController {
/**
* GET NoParameter
* @return
*/
@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;
}
/**
* GET TakeParameter
* @param id userId
* @return
*/
@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;
}
/**
* Post NoParameter
* @return
*/
@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;
}
/**
* Post TakeParameter
* @param id userId
* @return
*/
@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;
}
/**
* Post ObjectParameter
* @return
*/
@PostMapping("postObjectParamUser")
public Object postObjectParamUser(@RequestBody User user){
return user;
}
}
Interface documentation
Description | Request method | Request parameter | Request address |
---|---|---|---|
GET method, no parameters | GET | no | /user/getUser |
GET method, Int parameter | GET | Int(id) | /user/getParamUser |
Post method, no parameters | POST | no | /user/postNoParamUser |
Post method, with parameters | POST | Int(id) | /user/postParamUser |
Post method, Jsonized parameters | POST | Object(id,name,sex,studentId,sex,data) | /user/postObjectParamUser |
4. Write OkHttp tool class
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;
/**
* 发送网络请求
* @param url 请求Url
* @param context 上下文对象
* @param body 请求体,如果有请求体则发送Post请求,反之发送Get请求
*/
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());
}
});
}
/**
* 显示等待框
* @param context
*/
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();
}
}
}
Two, send the request
1. Send a Get request without parameters
Use tool classes to send network requests in your own business
//无参接口
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);
}
The print result is as follows
E/ApiData:: {"id":82,"name":"熊顺","studentId":"20181511011066","sex":"男","data":"Not have Parameter!" }
2. Send a Get request with parameters
When OkHttp sends a Get request, all request parameters are placed in the 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. Send a post request without parameters
You must bring the request body when sending a Post request
//无参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. Send a Pos request with participation
Fixed in add as String type
//有参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. Send Json data of Post
Sending Json data requires the help of JSONObject to convert the data into Json format
//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);
}