一、自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 请求拦截,校验header中秘钥
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckSecretkeyRequired {
}
二、被拦截的接口
/**
* 查询
* @param map
* @return
*/
@CheckSecretkeyRequired
@PostMapping("/getAll")
public Result getAll(@RequestParam Map<String, Object> map){
return Result.success(Arrays.asList());
}
三、拦截器
import com.cloud.industryapi.config.annotion.CheckSecretkeyRequired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SourceAccessInterceptor implements HandlerInterceptor {
@Value("${secret.key}")
private String secretKey;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod)handler;
CheckSecretkeyRequired loginRequired = handlerMethod.getMethod().getAnnotation(CheckSecretkeyRequired.class);
if(loginRequired == null){
return true;
}
String requestSecretKey = request.getHeader("secretKey");
if(secretKey.equals(requestSecretKey)) {
return true;
}else {
response.setContentType("application/json; charset=utf-8");
response.getWriter().print("你访问的资源秘钥不正确!");
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
四、Http请求工具类
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("all")
public class HttpsUtils {
public static String Method_GET = "GET";
public static String Method_POST = "POST";
public static String Method_PUT = "PUT";
public static String Method_DELETE = "DELETE";
/**
* Send SSL Request (发送请求带秘钥)(不包含get请求)
* @param reqURL
* @param str
* @param Secretkey 约定的秘钥,存Header里
* @return
* @throws IOException
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String sendSSLRequestIncludeSecretkey(String reqURL, Map<String, Object> params, String method, String Secretkey) {
String responseContent = null;
CloseableHttpClient client = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList <NameValuePair>();
if(params != null && params.size() > 0){
for (Map.Entry<String, Object> entry : params.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(
X509Certificate[] x509Certificates, String s)
throws CertificateException {
return true;
}
}).build();
//创建httpClient
client = HttpClients.custom().setSslcontext(sslContext).
setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpResponse response = null;
if (method.equals(Method_POST)) {
HttpPost httpPost = new HttpPost(reqURL);
httpPost.setEntity(formEntity);
httpPost.setHeader("dlhSecretkey",Secretkey);
response = client.execute(httpPost);
} else if (method.equals(Method_PUT)) {
HttpPut httpPut = new HttpPut(reqURL);
httpPut.setEntity(formEntity);
httpPut.setHeader("dlhSecretkey",Secretkey);
response = client.execute(httpPut);
} else if (method.equals(Method_DELETE)) {
HttpDelete httpDelete = new HttpDelete(reqURL);
httpDelete.setHeader("dlhSecretkey",Secretkey);
response = client.execute(httpDelete);
}
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseContent;
}
public static void main(String[] args) {
Map<String, Object> paramMap = new HashMap<>();
String secretKey = "secretKey";
String url = "url";
String response = HttpsUtils.sendSSLRequestIncludeSecretkey(url, paramMap, HttpsUtils.Method_POST, secretKey);
if (StringUtils.isNotEmpty(response)) {
Map<String, Object> returnMap = JSONObject.parseObject(response, new TypeReference<Map<String, Object>>() {});
String data = returnMap.get("data").toString();
List<entity> factoryDemoList = JSONObject.parseArray(data, entity.class);
}
}
}