两种方法实现调用post接口JSON请求体
以下两种方法都可以实现
方法一:
public JSONObject getVehicleList(){
JSONObject param = new JSONObject();
String url = "https://XXXX-gps.cn/video/webapi/user/login";
param.put("id","MjI3Ljg4NXXXXXX");
param.put("secret","6c714770be458e50a8c8e3e9ed3bb2d7");
HttpResponse response = HttpUtil.createPost(url)
.body(param.toString())
// .head()
.execute();
if (response.isOk()){
String body = response.body();
JSONObject bodyJson = JSONObject.parseObject(body);
try {
return bodyJson.getJSONObject("data");
} catch (Exception e){
return bodyJson.getJSONObject("data");
}
}
return param;
}
方法二:
public String getGPSLoginToken(){
String response = "";
String url = "https://XXXX-gps.cn/video/webapi/user/login";
String json = "{\"id\": \"MjI3Ljg4Ny4XXXXk\",\n" +
" \"secret\": \"6c714770be458e50a8c8e3e9ed3bb2d7\"\n" +"}";
try {
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
response += line;
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONObject.parseObject(response);
String token = jsonObject.getJSONObject("data").getString("token");
System.out.println("token = " + token);
return token;
}