When accessing a URL using java, if the URL requires authentication, it cannot be accessed directly because there is no login. So, how to solve this problem?
The method is to use java to simulate login, record the cookie information after logging in, and send the cookie to indicate the identity the next time you initiate a request, so that you can access the URL with permissions.
The following is the first step to introduce the use of java to simulate login.
// Connection address (obtained by reading the html source code, that is, the URL submitted by the login form) String surl = "http://login.goodjobs.cn/index.php/action/UserLogin"; /** * First, you need to talk to the URLConnection under the URL. URLConnection can be easily obtained from URLs. For example: // Using * java.net.URL and //java.net.URLConnection */ URL url = new URL(surl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /** * Then set the connection to output mode. URLConnection is usually used as input, such as downloading a web page. * By setting URLConnection to output, you can transfer data to your web page. Here is how to do it: */ connection.setDoOutput(true); /** * Finally, in order to get OutputStream, for simplicity, constrain it in Writer and put it in POST information, for example: ... */ OutputStreamWriter out = new OutputStreamWriter(connection .getOutputStream(), "GBK"); //The memberName and password are also known by reading the html code, that is, the corresponding parameter name in the form is out.write("memberName=myMemberName&password=myPassword"); // The key to post is! // remember to clean up out.flush(); out.close(); // Getting a cookie is equivalent to recording the identity, and it is used for use of String cookieVal = connection.getHeaderField("Set-Cookie");After logging in successfully, you can access other URLs.
String s = "http://user.goodjobs.cn/dispatcher.php/module/Resume/action/Preview"; //Reopen a connection url = new URL(s); HttpURLConnection resumeConnection = (HttpURLConnection) url .openConnection(); if (cookieVal != null) { //Send cookie information to indicate your identity, otherwise you will be deemed to have no permission resumeConnection.setRequestProperty("Cookie", cookieVal); } resumeConnection.connect(); InputStream urlStream = resumeConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(urlStream)); String ss = null; String total = ""; while ((ss = bufferedReader.readLine()) != null) { total += ss; } IOUtils.write(total, new FileOutputStream("d:/index.html")); bufferedReader.close(); Through the above method, you can access the URL with permission control. The idea is: simulate login, obtain a cookie to record your identity, and send a cookie to indicate your identity when requesting the next time.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.