在向我搭建的后台发送请求的时候,由于json参数结构比较复杂一直没有发送成功。
我发送的json参数格式如下:
{
"pre_prepare_in": {
"trace":{
"user_num": 10,
"contect": [
{"user":[1,2], "price_trade":12},
{"user":[2,3], "price_trade":12},
{"user":[3,4], "price_trade":12},
{"user":[4,5], "price_trade":12},
{"user":[5,6], "price_trade":12},
{"user":[6,7], "price_trade":12},
{"user":[7,8], "price_trade":12},
{"user":[8,9], "price_trade":12},
{"user":[9,0], "price_trade":12},
{"user":[0,1], "price_trade":12}]
},
"user_proassets":{
"user_num": 10,
"content": [
100,
100,
100,
100,
100,
100,
100,
100,
100,
100 ]
}
},
"block_num": 9,
"pointname": 1
}
该参数只能够被读取到block_num及pointname,而pre_prepare_in却显示为空。
后来我分析了原因,该参数A我发送的时候将参数封装成A类,A类下有三个属性,对应pre_prepare_in的属性被我定义为JSONObject类。问题就在这里,JSONObject类在post发送过程中会因为无法正常接收而丢失内容(我的发送方法不行可能也有别的方法,各路大神勿喷)。大概因为JSONObject这个类结构不固定,接收时没办法匹配字段。
所以就要将自己要发送的json文件的每个字段都在类内封装好。如下看我的代码:
//参数类A
public class Pre_prepare {
private Pre_prepare_in pre_prepare_in;
private Integer block_num;
private String pointname;
// get and set
}
//参数类A的子类B
public class Pre_prepare_in {
private RequestTrace trace;
private RequestProass user_proassets;
// get and set
}
//子类B的子类C
public class RequestTrace {
private Integer user_num;
private List<Trace_item> content;
// get and set
}
//子类B的子类D
public class RequestProass {
private Integer user_num;
private int[] content;
// get and set
}
//子类C的子类E
public class Trace_item {
private int[] user;
private Integer price_trade;
// get and set
}
post函数:
@SneakyThrows
private void dopost_preprepare(Pre_prepare pre_prepare,URL url){
HttpPost post = new HttpPost(url);
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
String pre_prepare_str = JSON.toJSONString(pre_prepare);
StringEntity stringEntity = new StringEntity(pre_prepare_str,StandardCharsets.UTF_8);
post.setEntity(stringEntity);
post.setHeader("Content-Type","application/json;charset=utf8");
try {
response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine.getStatusCode());
org.apache.http.HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity, StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
response.close();
client.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
接口:
@RestController
@RequestMapping("root")
public class threadController {
@PostMapping("pre_prepare")
public String getpre_prepare(@RequestBody Pre_prepare pre_prepare ){
System.out.println("收到请求");
return "内容" + pre_prepare;
}
过程当中需要注意的是字段要对应,用postman发送请求的时候也是一样,键值的名字要与类的属性名一样,否则也会出现接收不到内容为空的情况。