long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

Android-HTTP请求响应解析工具

Posted at 2022-09-26 android 

需求

请求的通用数据如下,

1
2
3
4
5
6
7
8
{
"request_id":1234,
"cmd":"RequestMethod",
"page":123,
"page_size":1234,
"body":{
}
}

其中body字段为特定请求方法的请求数据.
响应的通用数据如下

1
2
3
4
5
6
7
8
{
"code": 0,
"code_msg":"xxxx",
"request_id":12345,
"count":123,
"body":{
}
}

每个接口只需要关注body的内容,可能是object,字符串,数组。

设计实现

依赖

1
2
3
   implementation 'com.squareup.okhttp3:okhttp:3.14.7'
implementation 'com.squareup.okio:okio:1.17.5'
implementation group: 'com.alibaba.fastjson2', name: 'fastjson2', version: '2.0.12.android'

通用请求部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class CommonRequest<T> {

String cmd;
T body;
Integer page;
Integer page_size;

@JSONField(name = "request_id")
Integer requestId;

public CommonRequest(String cmd, T body) {
this.cmd = cmd;
this.body = body;
this.requestId = (int) ((Math.random() * 10000000)%100000);
}
// getter/setter 省略
}

通用响应部分

1
2
3
4
5
6
7
8
9
10
Integer code;
Integer request_id;
String code_msg;
T body;
Integer count;

public CommonResponse() {
}
// getter/setter省略
}

解析工具包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class HttpUtil<T> {
public static final MediaType JSON_TYPE = MediaType.get("application/json; charset=utf-8");

public T parseResponse(String str, Class<T> cls) throws Exception {
CommonResponse<T> comRes = JSON.parseObject(str, CommonResponse.class);
if (comRes.getCode() != 0) {
throw new Exception(String.format("code:%s, code_msg:%s", comRes.getCode(), comRes.getCode_msg()));
}
T res = JSON.to(cls, comRes.getBody());
return res;
}

public static String httpPostSync(String url, HashMap<String, String> header, String body) throws Exception {
OkHttpClient client = new OkHttpClient();
RequestBody reqBody = RequestBody.create(JSON_TYPE, body);
Request.Builder builder = new Request.Builder();
builder.url(url);
builder.post(reqBody);

if (header != null) {
header.forEach(builder::addHeader);
}
Request req = builder.build();
try (Response response = client.newCall(req).execute()) {
return response.body().string();
}
}
public static String httpPostSync(String url, String body) throws Exception {
return httpPostSync(url, null, body);
}
}

HelloWorld接口测试

请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class HelloWorldRequest {
String user;
Integer age;

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class HelloWorldResponse {
Integer id;
String addr;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getAddr() {
return addr;
}

public void setAddr(String addr) {
this.addr = addr;
}
}

api调用接口

1
2
3
4
5
6
7
8
9
public class HelloWorldApi {
public static final String url = "xxxx";
public static HelloWorldResponse run(HelloWorldRequest request) throws Exception {
CommonRequest<HelloWorldRequest> req = new CommonRequest<>("HelloWorld", request);
String requestBody = JSON.toJSONString(req);
String responseBody = HttpUtil.httpPostSync(url, null, requestBody);
return new HttpUtil<HelloWorldResponse>().parseResponse(responseBody, HelloWorldResponse.class);
}
}

单元测试
测试请求解析:

1
2
3
4
5
6
7
8
@Test
public void test_helloworld_request() throws Exception {
HelloWorldRequest request = new HelloWorldRequest();
request.setAge(12);
request.setUser("hello");
String requestStr = JSON.toJSONString(new CommonRequest<HelloWorldRequest>("HelloWorld", request));
System.out.println("request: "+ requestStr);
}

输出

1
request: {"body":{"age":12,"user":"hello"},"cmd":"HelloWorld","request_id":17993}

测试响应解析:

1
2
3
4
5
public void test_helloworld_response() throws Exception {
String responseStr = "\"code\":0,\"code_msg\":\"\",\"count\":0,\"request_id\":0,\"body\":{\"id\":3213,\"addr\":\"world\"}}";
HelloWorldResponse response = new HttpUtil<HelloWorldResponse>().parseResponse(responseStr, HelloWorldResponse.class);
System.out.println(JSON.toJSONString(response));
}

输出:

1
{"addr":"world","id":3213}

Share 

 Previous post: Android-Toast组件 Next post: 重启wsl 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo