正文
http post url参数封装(key token 及校验码)
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
post请求本来是一种很常见的web请求方式,相信许多项目都有一系列的封装工具类。
今天遇着一个特殊的需求。
需要在post的请求url内封装相应的token 与及key相关的值,这就奇怪了,url封装相应的参数值不是get的做法么,post可以支持么 ,试试,例如Postman等常用的restful接口测试工具都能够调用成功,但是原来封装的普通的http的post方法,便不再能够正常支持参数的 封装,要么校验报错,或者说是直接提示url不符合规范。
常用的请求方式是httpClient 与HttpURLConnection:
首先列出我们需要封装入url的请求token:
如果只是简单拼接进url是行不通的,因为我们都知道URLEncoder,对url字符集编码设置,所以需要对所有的值进行字符集编码设置,最终我们封装成了如下post方法支持url拼接入相应的请求参数:
POST_URL:请求url
urlParam:如上需要封装进url的参数
body:普通需要传递的参数
public static String httpURLConnectionPOST (String POST_URL,Map<String, String> urlParam,String body) { CloseableHttpResponse response = null;
try {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout()
.setConnectTimeout()
.setConnectionRequestTimeout()
.build();
//httpclient
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// HttpPost httpPost = new HttpPost(POST_URL);
StringBuilder param=new StringBuilder("");
//将要拼接的参数urlencode
for (String key:urlParam.keySet()){
param.append(key + "=" + URLEncoder.encode(urlParam.get(key), "UTF-8") + "&");
}
//pingjie
HttpPost httpPost = new HttpPost(POST_URL+param.toString());
//请求参数设置
if(com.sf.ccsp.common.util.StringUtils.isNotEmpty(body)){
StringEntity entity=new StringEntity(body, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
}
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
} catch (ClientProtocolException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (Exception e){
System.out.println(e);
}finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
} } return null; }
这样就可以正常调用了。
那么问题来了,对方为什么要这样做呢?
想了一下,1.处于安全性验证它的access_token是一个时效性非常高的校验,防止可重入攻击
2.url中的参数值方便多次获取校验