java
<!-- 其他依赖(如 JSON 解析) -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
java
package com.tools;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSONObject;
public class ApiClient {
//将json字符串解析成json格式
public static void main(String[] args) {
// TODO Auto-generated method stub
//{"Name":"CICI","Phone":"18501680095","Img":"http://pwxvr.com/dreame/statics/uploadfiles/1773206309811.jpg","BU":"","code":200,"msg":"查询用户信息成功"}
String jsonData = getUserData("D00001");
System.out.println(jsonData);
JSONObject jsonObject = JSONObject.parseObject(jsonData);
String code = jsonObject.getString("code");
System.out.println("code: " + code); // 输出:code: 200(查询成功) 、其他的数字,代表查询失败
String name = jsonObject.getString("Name");
System.out.println("Name: " + name); // 输出:Name: CICI
String bu = jsonObject.getString("BU");
System.out.println("BU: " + bu); // 输出:BU: 用户的BU名称
String img = jsonObject.getString("Img");
System.out.println("Img: " + img); // 输出Img: 头像路径
}
public static String getUserData(String cardId) {
HttpURLConnection connection = null;
try {
// 构建URL
String urlStr = "http://pwx.com/dreame/ac/selectPlaceuser.json?cardId=" + cardId;
URL url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8")
);
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
}