这里调用的是微信检测是否违规文字,因为头部需要带上token参数,然后还需要JSON格式的数据
public static void main(String[] args){
private static final String MSG_SEC_CHECK = "需要请求的接口URL?参数=%s";
Map<String, Object> map = new HashMap<>(1);
map.put("content", msg);
// 替换 url 中的 %s 按顺序替换
String format = String.format(MSG_SEC_CHECK, token);
StringBuffer sb = new StringBuffer();
// 转换为JSONobject对象 可以使用阿里的JSON工具包
JSONObject json= JSONUtil.parseObj(map);
// 出于好奇打印了转换后的对象 格式为: {"键":"值"}
log.info("------map{}", jsonObject1);
try {
URL url = new URL(format);
//创建httpsclient对象 还可以创建httpclient对象
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
// 设置允许输入
conn.setDoInput(true);
// Post 请求不能使用缓存
conn.setUseCaches(false);
// 设置传递方式
conn.setRequestMethod("POST");
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
byte[] data = (json.toString()).getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 设置文件类型:
conn.setRequestProperty("contentType", "application/json");
// 开始连接请求
conn.connect();
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 写入请求的字符串
out.write((json.toString()).getBytes());
out.flush();
out.close();
// 请求的状态码
//System.out.println(conn.getResponseCode());
// 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
System.out.println("连接成功");
// 请求返回的数据
InputStream in1 = conn.getInputStream();
try {
String readLine;
// 读数据
BufferedReader responseReader = new BufferedReader(new InputStreamReader(in1, StandardCharsets.UTF_8));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
log.info("------拼接中{}", sb);
}
// 拼接后的最终结果
//System.out.println(sb);
// 关流
responseReader.close();
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
System.out.println("error++");
}
} catch (Exception e) {
e.printStackTrace();
}
// 将拼接好的字符串转换为JSONobject 便于取值
JSONObject jsonObject2 = JSONUtil.parseObj(sb);
// 获取到状态码返回结果
return jsonObject2.getInt(CODE);
}
}