http post請求url封裝相應的key token 及校正碼

來源:互聯網
上載者:User

標籤:測試   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 及校正碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.