JSP開發(fā)中Apache-HTTPClient 用戶驗證的實例詳解
JSP開發(fā)中Apache-HTTPClient 用戶驗證的實例詳解
前言:
在微服務(wù)框架之外的系統(tǒng)中,我們經(jīng)常會遇到使用httpClient進(jìn)行接口調(diào)用的問題,除了進(jìn)行白名單的設(shè)置,很多時候我們需要在接口調(diào)用的時候需要身份認(rèn)證。翻了一下官方文檔,解決方法很多,但是都不太符合實際業(yè)務(wù)場景,這里提供一種簡單粗暴的解決方法。
解決方法:利用請求頭,將驗證信息保存起來。
實現(xiàn)代碼:
public class HttpClientUtils { protected static final Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class); private static final String AUTHENKEY = "Authorization"; private static final String BASICKEY = "Basic "; public static String getConnect(String url,String username,String password) { CloseableHttpResponse response = null; CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); Base64 token = new Base64(); String authenticationEncoding = token.encodeAsString(new String(username + ":" + password).getBytes()); httpGet.setHeader(AUTHENKEY, BASICKEY + authenticationEncoding); String responseContent = ""; try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e) { LOG.error(e.toString()); } finally { if (response != null) { try { response.close(); } catch (IOException e) { LOG.error(e.toString()); } } if (client != null) { try { client.close(); } catch (IOException e) { LOG.error(e.toString()); } } } return responseContent; } }
以上就是Apache-HTTPClient 用戶驗證的實例,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
在 Linux 上安裝Apache+ApacheJServ+JSP
在 Linux 上安裝Apache+ApacheJServ+JSP...2006-10-10Spring獲取ApplicationContext對象工具類的實現(xiàn)方法
這篇文章主要介紹了 Spring獲取ApplicationContext對象工具類的實現(xiàn)方法的相關(guān)資料,希望通過本文能幫助到大家,讓大家實現(xiàn)這樣的功能,需要的朋友可以參考下2017-10-10在JSP中訪問MS SQL Server數(shù)據(jù)庫
在JSP中訪問MS SQL Server數(shù)據(jù)庫...2006-10-10jsp獲取action傳來的session和session清空以及判斷
這篇文章主要介紹了jsp獲取action傳來的session和session清空以及判斷,需要的朋友可以參考下2014-03-03