android Simple encapsulation and use of get and post requests for okHttp
- 2021-12-12 09:56:33
- OfStack
Due to the need of Android course project, I specially consulted the use of okHttp, and found that Otawa's own needs found online are different. Therefore, according to the needs of the team project, I simply encapsulated an get and post request of okHttp.
Don't say much, just look at the code!
1. Attribute encapsulation needed in the early stage
private static Request request = null;
private static Call call = null;
private static int TimeOut = 120;
// Singleton acquisition ohttp3 Object
private static OkHttpClient client = null;
/**
* OkHttpClient The construction method of thread lock is used to construct
* @return OkHttpClient Object
*/
private static synchronized OkHttpClient getInstance() {
if (client == null) {
client = new OkHttpClient.Builder()
.readTimeout(TimeOut, TimeUnit.SECONDS)
.connectTimeout(TimeOut, TimeUnit.SECONDS)
.writeTimeout(TimeOut, TimeUnit.SECONDS)
.build();
}
return client;
}
/**
* callback Interface
* Used when asynchronous requests are made
*/
static class MyCallBack implements Callback {
private OkHttpCallback okHttpCallBack;
public MyCallBack(OkHttpCallback okHttpCallBack) {
this.okHttpCallBack = okHttpCallBack;
}
@Override
public void onFailure(Call call, IOException e) {
okHttpCallBack.onFailure(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
okHttpCallBack.onSuccess(response);
}
}
/**
* Get synchronization get Request object Response
* @param url
* @return Response
*/
private static Response doSyncGet(String url) {
// Create OkHttpClient Object
client = getInstance();
request = new Request.Builder()
.url(url)// Request link
.build();// Create Request Object
try {
// Get Response Object
Response response = client.newCall(request).execute();
return response;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Get asynchronous get Request object
* @param url Request address
* @param callback Realization callback Interface
*/
private static void doAsyncGet(String url,OkHttpCallback callback) {
MyCallBack myCallback = new MyCallBack(callback);
client = getInstance();
request = new Request.Builder()
.url(url)
.get()
.build();
client.newCall(request).enqueue(myCallback);
}
Where the OKHttpCallback interface is:
import java.io.IOException;
import okhttp3.Response;
public interface OkHttpCallback {
void onFailure(IOException e);
void onSuccess(Response response);
}
2. get Request Encapsulation
1. The project requirement is to interact with strings in json format throughout the whole process, so the following is encapsulated for json.
2. Under the explanation 1 here, the return is a string type, which indicates the json string returned in the background. In addition, why should list be used to define the return value result, and result. get (0) is the value of return, because directly using String to define result will report an error, and the specific reason is unknown. . . .
(1) Synchronize get requests
/**
* Synchronization get Request
* For example, the final address of the request is: http://127.0.0.1:8081/user/getUser/123
* @param url Basic request address Examples: http://127.0.0.1:8081
* @param args Parameters requested args[]=new String[]{"user","getUser","123"}
* @return String
*/
public static String getSyncRequest(String url,String... args) {
List<String> result=new ArrayList<>();// Return value
String address=url;
for(int i=0;i<args.length;i++){
address=address+"/"+args[i];
}
final String finalAddress = address;
new Thread(new Runnable() {
@Override
public void run() {
Response finalResponse = doSyncGet(finalAddress);
String res = null;
try {
Log.d(" Synchronization get Request Request Address: ",finalAddress);
if (finalResponse.isSuccessful()) {// Request succeeded
ResponseBody body = finalResponse.body();// Get the response body
res = body.string();
result.add(res);
Log.d("HttpUtil", " Synchronization get Request succeeded! ");
Log.d(" Request object: ", res);
} else {
Log.d("HttpUtil", " Synchronization get Request failed! ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
/** Because the function return is executed immediately, and result You can't get it until the request is completed
* So we need to wait result Get the return value before executing return*/
while(result.size()==0){
try {
TimeUnit.MILLISECONDS.sleep(10);// Wait xx Milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result.get(0);
}
(2) Asynchronous get requests
/**
* Asynchronous get Request
* For example, the final address of the request is: http://127.0.0.1:8081/user/getUser/123
* @param url Basic request address Examples: http://127.0.0.1:8081
* @param args Parameters requested args[]=new String[]{"user","getUser","123"}
* @return String
*/
public static String getAsyncRequest(String url,String... args){
List<String> result=new ArrayList<>();
String address=url;
for(int i=0;i<args.length;i++){
address=address+"/"+args[i];
}
final String finalAddress = address;
doAsyncGet(finalAddress, new OkHttpCallback() {
@Override
public void onFailure(IOException e) {
Log.d(" Asynchronous get Request address: ",finalAddress);
Log.d("HttpUtil", " Asynchronous get Request failed! ");
}
@Override
public void onSuccess(Response response) {
Log.d(" Asynchronous get Request address: ",finalAddress);
String res = null;
try {
res = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
result.add(res);
Log.d("HttpUtil", " Asynchronous get Request succeeded! ");
Log.d(" Request object: ", res);
}
});
/** Because the function return is executed immediately, and result You can't get it until the request is completed
* So we need to wait result Get the return value before executing return*/
while(result.size()==0){
try {
TimeUnit.MILLISECONDS.sleep(10);// Wait xx Milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result.get(0);
}
3. post request
In this illustration 1, the back end receives a string whose name is "json". In fact, it transmits an json string as the data in the request form. The back end performs the next step by parsing the json string
(1) Synchronize post requests
/**
* Synchronization post Request
* For example, the final address of the request is: http://127.0.0.1:8081/user/getUser/123
* @param url Basic request address Examples: http://127.0.0.1:8081
* @param json Submitted json String
* @param args Parameters requested args[]=new String[]{"user","getUser","123"}
* @return
*/
public static String postSyncRequest(String url,String json,String... args){
List<String> result=new ArrayList<>();
String address=url;
for(int i=0;i<args.length;i++){
address=address+"/"+args[i];
}
final String finalAddress = address;
new Thread(new Runnable() {
@Override
public void run() {
client=getInstance();
Log.d(" Synchronization post Request address: ",finalAddress);
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("json",json);
request=new Request.Builder()
.url(finalAddress)
.post(formBody.build())
.addHeader("device-platform", "android")
.build();
try{
Response response=client.newCall(request).execute();
String res=response.body().string();
result.add(res);
Log.d("HttpUtil", " Synchronization post Request succeeded! ");
Log.d(" Request object: ", res);
}catch (Exception e){
Log.d("HttpUtil", " Synchronization post Request failed! ");
e.printStackTrace();
}
}
}).start();
/** Because the function return is executed immediately, and result You can't get it until the request is completed
* So we need to wait result Get the return value before executing return*/
while(result.size()==0){
try {
TimeUnit.MILLISECONDS.sleep(10);// Wait xx Milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result.get(0);
}
(2) Asynchronous post requests
/**
* Asynchronous post Request
* For example, the final address of the request is: http://127.0.0.1:8081/user/getUser/123
* @param url Basic request address Examples: http://127.0.0.1:8081
* @param json Submitted json String
* @param args Parameters requested args[]=new String[]{"user","getUser","123"}
* @return
*/
public static String postAsyncRequest(String url,String json,String... args){
List<String> result=new ArrayList<>();
String address=url;
for(int i=0;i<args.length;i++){
address=address+"/"+args[i];
}
final String finalAddress = address;
Log.d(" Synchronization post Request address: ",finalAddress);
client=getInstance();
FormBody.Builder formBody = new FormBody.Builder();// Create a form request body
formBody.add("json",json);
request = new Request.Builder()
.url(finalAddress)
.post(formBody.build())
.addHeader("device-platform", "android")
.build();
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d("HttpUtil"," Asynchronous post Request failed! ");
}
}).start();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
new Thread(new Runnable() {
@Override
public void run() {
String res = null;
try {
res = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
result.add(res);
Log.d("HttpUtil"," Asynchronous post Request succeeded! ");
Log.d(" Request object ",res);
}
}).start();
}
});
/** Because the function return is executed immediately, and result You can't get it until the request is completed
* So we need to wait result Get the return value before executing return*/
while(result.size()==0){
try {
TimeUnit.MILLISECONDS.sleep(10);// Wait xx Milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result.get(0);
}
4. Dependencies and related descriptions
The related dependencies are: (okHttp and Gson)
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
implementation 'com.google.code.gson:gson:2.7'
Since canceling the delay will cause result to proceed to return before return is assigned, a delay is added in each request method before return is assigned until result is assigned before return is executed
The next article is about how android interacts with the backend through okHttp, and related examples.