轉:使用基本認證從WebServer獲取資料
轉:使用基本認證從WebServer獲取資料
[@more@]/** * This class sends request to the specified URL and reads the response. * * Uses basic authentication to authenticate with the Server and writes the * request to the specified URL. Response can be either be read as an Object or * as BinaryStream or as AsciiStream. * */ public class ServletUtils { private static final int BUFFSIZE = 4 * 1024; // buffer size - 4K /** * Default Constructor. */ public ServletUtils() { } /** * This method establishes connection to the specified server and authenticates * using the specified username and password. * * @param servletUrl URL of the server to send request * @param username user name to be used for authentication with server * @param password password to be user for authentication with server * * @return URLConnection instance of connection to the specified server */ public HttpURLConnection getServerConnection( String server, String username, String password ) throws Exception { HttpURLConnection urlConn = null; URL url = new URL(server); // Build the string to be used for Basic Authentication: String userPassword = username + ":" + password; // Base64 encode the authentication string String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); //URLConnection urlConn = (HttpURLConnection) url.openConnection(); // Enable writing to server ( to write request ) urlConn.setDoOutput(true); // Enable reading from server ( to read response ) urlConn.setDoInput(true); // Disable cache urlConn.setUseCaches(false); urlConn.setDefaultUseCaches(false); // Set Basic Authentication parameters urlConn.setRequestProperty ("Authorization", "Basic " + encoding); return urlConn; } /** * This method sends the specified request to the given url and returns the * response as an Object. If the returned Object is an instance of * CMSAccessException, throws it. * * @param req HttpServletRequest that has to be sent to the server * @param servletUrl URL of the server to send request * @param username user name to be used for authentication with server * @param password password to be user for authentication with server * * @return Response from the server * * @exception CMSAccessException if server could not handle the request */ public Object sendRequest(HttpServletRequest req, String servletUrl, String username, String password) throws CMSAccessException { // Response from server Object responseObj = null; HttpURLConnection urlConn = null; try { String res = "Nothing was returned"; System.out.println( "*************" ); System.out.println( "Username : " + username ); System.out.println( "Password : " + password ); urlConn = this.getServerConnection(servletUrl, username, password); System.out.println( "ServletURL : " + servletUrl ); System.out.println( "*************" ); String contenttype = req.getHeader( "Content-Type" ); // Set Content Type if (contenttype != null) { urlConn.setRequestProperty("Content-Type", contenttype); } else { urlConn.setRequestProperty("Content-Type", "text/plain"); } // Get output stream of server to send the request BufferedOutputStream connOut = new BufferedOutputStream(urlConn.getOutputStream()); System.out.println( "bef urlconn" ); // Establish connection to server urlConn.connect(); byte[] buffer = new byte[ BUFFSIZE ]; int len = 0; System.out.println( "get input stream" ); // Get the input stream for request ServletInputStream in = req.getInputStream(); System.out.println( "read and write" ); // Write request while ((len = in.read(buffer,0,buffer.length )) >-1) { connOut.write(buffer,0,len); } System.out.println( "done writing ..." ); // Close connOut.flush(); connOut.close(); in.close(); // Completed sending request, now read response System.out.println( "output stream" ); // Read the object send by server ObjectInputStream inputFromServlet = new ObjectInputStream(urlConn.getInputStream()); System.out.println( "bef readobj" ); responseObj = inputFromServlet.readObject(); System.out.println( "readobj done..." ); inputFromServlet.close(); } catch (Exception ex) { throw new CMSAccessException ( "Error sending request : " + ex.toString() ); } finally { // Disconnect if( urlConn != null ) { urlConn.disconnect(); urlConn = null; } } // Check if response is an error message if ( responseObj instanceof CMSAccessException ) { throw (CMSAccessException)responseObj; } return responseObj; } /** * This method sends the specified request to XDB server and returns the * response as a String. The request would be for a particular file, XDB * server responds with the contents of the file which is returned by this method. * * Uses the Authenticator class to authenticate with XDB server. * * @param req HttpServletRequest that has to be sent to the server * @param servletUrl URL of the server to send request * @param username user name to be used for authentication with server * @param password password to be user for authentication with server * * @return File contents of the specified file * * @exception CMSAccessException if server could not handle the request */ public String sendXDBServletRequest(HttpServletRequest req, String servletUrl, String username, String password) throws CMSAccessException { HttpURLConnection urlConn = null; StringBuffer sb = new StringBuffer(); try { URL url = new URL(servletUrl); // Use Authenticator to provide authentication info to XDB servlet Authenticator.setDefault(new AuthImpl(username,password)); //URLConnection urlConn = (HttpURLConnection) url.openConnection(); // Enable writing to server ( to write request ) urlConn.setDoOutput(true); // Enable reading from server ( to read response ) urlConn.setDoInput(true); // Get output stream of server to send the request BufferedOutputStream connOut = new BufferedOutputStream(urlConn.getOutputStream()); urlConn.connect(); byte[] buffer = new byte[ BUFFSIZE ]; int len = 0; // Get the input stream for request ServletInputStream in = req.getInputStream(); // Write request while ((len = in.read(buffer,0,buffer.length )) >-1) { connOut.write(buffer,0,len); } // Close connOut.flush(); connOut.close(); in.close(); // Completed sending request, now read response // Get handle to server response InputStream content = (InputStream) url.getContent(); BufferedReader servletin = new BufferedReader(new InputStreamReader(content)); String line = null; // Read contents from XDB server while ((line = servletin.readLine()) != null) { sb.append(line); sb.append('n'); } servletin.close(); } catch (Exception ex) { throw new CMSAccessException ( "Exception at sendXDBServletRequest method : " + ex.toString() ); } finally { // Disconnect if( urlConn != null ) { urlConn.disconnect(); urlConn = null; } } return sb.toString(); } /** * This method sends the specified request using GET method to server and * writes the response to the specified HttpServletResponse. * * @param res HttpServletResponse to which server response has to be written * @param servletUrl URL of the server to send request * @param username user name to be used for authentication with server * @param password password to be user for authentication with server * * @exception CMSAccessException if server could not handle the request */ public void sendXDBServletRequest(HttpServletResponse res, String servletUrl, String username, String password) throws CMSAccessException { HttpURLConnection urlConn = null; BufferedInputStream in = null; BufferedOutputStream bout = null; try { // Authenticate with server and get connection urlConn = this.getServerConnection(servletUrl, username, password); byte[] buffer = new byte[ BUFFSIZE ]; int len = 0; // Get response from server in = new BufferedInputStream( urlConn.getInputStream( ) ); // Set response content type res.setContentType( urlConn.getContentType() ); // Get handle to response output stream bout = new BufferedOutputStream( res.getOutputStream( ) ); // Reads from server and write to response while( ( len = in.read(buffer,0,buffer.length) ) > -1 ) { bout.write(buffer, 0, len ); } } catch (IOException ioEx) { System.out.println( " IO Error occured while communicating with server : " + ioEx.toString( ) ); } catch (Exception ex) { throw new CMSAccessException ( "Error communicating with server : " + ex.toString() ); } finally { try { if( in != null ) in.close(); if( bout != null ) bout.close(); } catch(IOException ioEx) { System.out.println(" Error closing streams : " + ioEx.toString()); } // Disconnect if( urlConn != null ) { urlConn.disconnect(); urlConn = null; } } } // Inner class /** * This inner class is invoked whenever a server requires Authentication. */ class AuthImpl extends Authenticator { private String user=null; private String pwd = null; /** * Constructs a new Authenticator object with the specified username and * password. * * @param user username for authentication * @param pass password for authentication */ public AuthImpl(String user,String pass) { this.user = user; this.pwd = pass; } /** * This method is invoked if the server requests authentication information. * * @return user credentials for authentication */ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pwd.toCharArray()); } } // End of Inner class } Trackback:
http://anotherbug.blog.chinajavaworld.com/entry/4060/15
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220284/viewspace-1010912/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 從session中獲取資料Session
- 使用捕獲 獲取身份證號的資訊
- 獲取微信使用者基本資訊
- 從 falcon api 中獲取資料API
- 大陸居民身份證、港澳臺居民居住證 Composer 包:驗證、獲取基本資訊以及生成假資料
- 解決 Laravel JWT 多表認證時獲取不到當前認證使用者的問題LaravelJWT
- datatables使用ajax獲取資料
- ADAMoracle從根本上保證了資料獲取的去中心化性Oracle中心化
- electron + go 如何從sqlite獲取資料GoSQLite
- Http基本認證HTTP
- HTTP認證之基本認證——Basic(一)HTTP
- HTTP認證之基本認證——Basic(二)HTTP
- 使用API介面獲取商品資料:從入門到實踐API
- http authorization 基本認證HTTP
- 使用 Docker CertBot 獲取 SSL 證書Docker
- 教你如何使用API介面獲取資料!API
- 登入驗證判斷,獲取後臺資料
- 獲取.crt證書的資訊
- 使用 useLazyFetch 進行非同步資料獲取非同步
- 使用Python獲取HTTP請求頭資料PythonHTTP
- SSL認證 request.getScheme() 獲取不到https的問題SchemeHTTP
- 從RPA獲得資本市場認可,看AI大資料投資AI大資料
- CAS配置資料庫,實現資料庫使用者認證資料庫
- 如何獲得PMP認證證書
- 登入介面:從資料庫中獲取資訊驗證登入(與註冊介面相聯絡)資料庫
- 使用商品詳情API介面獲取商品資料API
- 如何使用API介面獲取淘寶商品資料API
- 【Spring Boot】使用JDBC 獲取相關的資料Spring BootJDBC
- 如何使用js獲取USB掃碼槍資料JS
- Android使用Camera2獲取預覽資料Android
- modbustcp封裝使用獲取裝置資料示例TCP封裝
- 使用**迭代器**獲取Cifar等常用資料集
- keycloak~RequiredActionProvider中獲取表單認證前URL的引數UIIDE
- 深入Spring Security-獲取認證機制核心原理講解Spring
- python 從mongodb中獲取資料載入到pandas中PythonMongoDB
- Modbus ASCII 獲取資料ASCII
- Python獲取jsonp資料PythonJSON
- 1.獲取資料
- 獲取Wireshark資料流