在開發程序的過程中,我們經常遇到調用接口的問題,很多時候我們還需要在調用接口時進行身份驗證,今天就讓錯新技術頻道小編和大家詳解JSP開發中Apache-HTTPClient 用戶驗證的方法,希望對你有所幫助。
詳解JSP開發中Apache-HTTPClient 用戶驗證的方法
解決方法:利用請求頭,將驗證信息保存起來。
實現代碼:
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; }}本文是錯新技術頻道小編給大家帶來的詳解JSP開發中Apache-HTTPClient 用戶驗證的方法,相信大家都有所了解,想要學習到更多的專業知識,歡迎關注錯新技術頻道小編為大家帶來的推薦。
新聞熱點
疑難解答