Obtain session information from the logon process

Source: Internet
Author: User

private static final String loginUrl = "http://42.120.50.206/apr/login.php";private String sessionId;public boolean login(String username, String password) {                                                       Map<String, String> params = new HashMap<String, String>();        params.put("username", username);        params.put("password", password);                                                       HttpURLConnection connection = null;                                               try {            connection = doPost2(loginUrl, params);            if (connection == null) {                return false;            }                                                       String key = "";                                                       if (connection != null) {                for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {                    //System.out.println("key: " + key);                    if (key.equalsIgnoreCase("set-cookie")) {                        sessionId = connection.getHeaderField(key);                        sessionId = sessionId.substring(0, sessionId.indexOf(";"));                        //System.out.println("sessionId: " + sessionId);                    }                 }                                                               InputStream is = connection.getInputStream();                String result = getResult(is);                System.out.println("result: " + result);                                                               if (sessionId != null) {                    return true;                }            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (connection != null) {                connection.disconnect();            }          }                                               return false;    }


Public HttpURLConnection doPost2 (String urlStr, Map <String, String> params) throws IOException {StringBuilder sb = new StringBuilder (); for (Map. entry <String, String> param: params. entrySet () {sb. append (param. getKey ()). append ("= "). append (param. getValue ()). append ("&");} int len = sb. length (); if (len> 0) {sb. deleteCharAt (len-1);} String args = sb. toString (); // System. out. println ("args:" + Args); return doPost2 (urlStr, args);}/*** @ param args * @ throws IOException * @ throws UnsupportedEncodingException */public HttpURLConnection doPost2 (String urlStr, String args) throws IOException {URL url = null; try {url = new URL (urlStr);} catch (MalformedURLException e) {e. printStackTrace (); return null;} HttpURLConnection connection = (HttpURLConnection) url. openConnection (); // simulates the browser, Can have no connection. setRequestProperty ("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv: 7.0.1) Gecko/20100101 Firefox/7.0.1"); // This line is critical, this line of connection is required for login. setInstanceFollowRedirects (false); connection. setConnectTimeout (10000);/*** then set the connection to the output mode. URLConnection is usually used as input, such as downloading a Web page. * By setting URLConnection as output, you can transmit data to your web page. How to do this: */connection. setDoOutput (true); // connection. setRequestMethod ("POST");/*** finally, to get OutputStream, put it in Writer and put it into POST information for simplicity, for example :... */OutputStreamWriter out = new OutputStreamWriter (connection. getOutputStream (), "UTF-8"); out. write (args); // transmits data to the page. The key to post! // Remember to clean up out. flush (); out. close (); return connection ;}
private static String getResult(InputStream is) throws IOException {    StringBuilder sb = new StringBuilder();                               BufferedReader br = new BufferedReader(new InputStreamReader(               is));                                  String line = null;    while ((line = br.readLine()) != null) {           sb.append(line).append("\r\n");       }                                  return sb.toString();}


This article is from "recalling the past ..." Blog, please be sure to keep this source http://memory.blog.51cto.com/6054201/1288701

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.