標籤:測試 request public 擷取 catch keyset style efault res
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中的參數值方便多次擷取校正
http post請求url封裝相應的key token 及校正碼