import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName: SecurityCheckController
* @Description: QQ安全校验
* @author: limingxing
* @Date: 2020-08-07 19:27
*/
@Slf4j
public class SecurityCheckController {
/**
* 获取access_token地址
*/
private static final String QQ_GET_ACCESS_TOKEN = "https://api.q.qq.com/api/getToken?grant_type=client_credential&appid=%s&secret=%s";
/**
* 校验图片是否含有违法违规内容。
*/
private static final String QQ_IMGSECCHECK_URL = "https://api.q.qq.com/api/json/security/ImgSecCheck?access_token=%s";
/**
* QQ安全文本校验
*/
private static final String QQ_MSGSECCHECK_URL = "https://api.q.qq.com/api/json/security/MsgSecCheck?access_token=%s";
/**
* 异步校验图片/音频URl
*/
private static final String QQ_MEDIACHECKASYNC = "https://api.q.qq.com/api/json/security/MediaCheckAsync?access_token=%s";
private static final String appid = "";
private static final String secret = "";
/**
* 获取QQ的AccessToken
*
* @return
*/
private String getAccessToken() {
try {
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(String.format(QQ_GET_ACCESS_TOKEN, appid, secret), null, String.class);
JSONObject jsonObject = JSONObject.parseObject(result);
return jsonObject.getString("access_token");
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* QQ小程序校验内容
*
* @param content
* @return
*/
@GetMapping("/qq/msgSecCheck")
public Object msgSecCheck(String content) {
String accessToken = getAccessToken();
String url = String.format(QQ_MSGSECCHECK_URL, accessToken);
RestTemplate restTemplate = new RestTemplate();
JSONObject object = new JSONObject();
object.put("content", content);
String result = restTemplate.postForObject(url, object, String.class);
log.info("SecurityCheckController.qqMsgSecCheck result: {}", result);
JSONObject jsonObject = JSONObject.parseObject(result);
jsonObject.put("errcode", jsonObject.getString("errCode"));
return jsonObject;
}
/**
* QQ小程序校验图片
*
* @param multipartFile
* @return
*/
@GetMapping("/qq/imgSecCheck")
public Object imgSecCheck(MultipartFile multipartFile) throws Exception {
String accessToken = getAccessToken();
String url = String.format(QQ_IMGSECCHECK_URL, accessToken);
//传地址执行getFileStream
// InputStream inputStream = getFileStream(imgUrl);
InputStream inputStream = multipartFile.getInputStream();
Map<String, ContentBody> param = new HashMap<>();
param.put("media", new InputStreamBody(inputStream, "img.jpg"));
String result = doPostFileMultiPart(url, param);
JSONObject jsonObject = JSONObject.parseObject(result);
log.info("imgSecCheck jsonObject: [{}]", jsonObject);
return jsonObject;
}
/**
* QQ小程序校验图片/音频
* 需要配置异步检测结果方法, 在 30 分钟内会推送到消息接收服务器
*
* @param mediaUrl 要检测的多媒体url
* @param mediaType 1:音频;2:图片
* @return
*/
public String mediaCheckAsync(String mediaUrl, String mediaType) {
String accessToken = getAccessToken();
JSONObject body = new JSONObject();
body.put("media_type", mediaType);
body.put("media_url", mediaUrl);
log.info("mediaCheckAsync body: [{}]", body);
String url = String.format(QQ_MEDIACHECKASYNC, accessToken);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(url, body, String.class);
log.info("mediaCheckAsync result: [{}]", result);
org.json.JSONObject jsonObject = new org.json.JSONObject(result);
String traceId = String.valueOf(jsonObject.get("trace_id"));
return traceId;
}
/**
* QQ异步校验图片/音频回调
*
* @param content
*/
public void qqMediaCheckAsyncCallback(String content) {
try {
JSONObject jsonObject = JSONObject.parseObject(content);
String traceId = jsonObject.getString("trace_id");
Integer isrisky = jsonObject.getIntValue("isrisky");
//检测结果,0:暂未检测到风险,1:风险
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过图片url返回InputStream
*
* @param path
* @return
*/
public static InputStream getFileStream(String path) {
URL url = null;
InputStream is = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //利用HttpURLConnection对象,我们可以从网络中获取网页数据.
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream(); //得到网络返回的输入流
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
/**
* 请求QQ安全校验封装
*
* @param url
* @param bodyMap
* @return
* @throws IOException
*/
public static String doPostFileMultiPart(String url, Map<String, ContentBody> bodyMap) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(url);
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
httppost.setConfig(defaultRequestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (Map.Entry<String, ContentBody> param : bodyMap.entrySet()) {
multipartEntityBuilder.addPart(param.getKey(), param.getValue());
}
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
log.info("return doPostFileMultiPart: [{}]", entity);
return EntityUtils.toString(entity, Charset.forName("UTF-8"));
}
} finally {
response.close();
}
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
QQ 小程序内容安全校验
最新推荐文章于 2023-01-20 09:52:03 发布