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(6000) .setConnectTimeout(6000) .setConnectionRequestTimeout(6000) .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中的參數值方便多次獲取校驗