java web landing httpClient simulation and save the cookie

Scene: call interface to complete an operation, but the interface is strong logged in, you need cookie, and the cookie will expire; servers limit the number of login, if an account log in frequently, you can not log normal in a short time, and therefore can not be done each time you call interface to log in once, and such efficiency will be relatively low;

Methods: acquiring httpClient cookie, and the cookie added check on the interface;

Core code:

0. need to add the jar package

 

 1 import org.apache.commons.lang.StringUtils;
 2 import org.apache.commons.httpclient.HttpClient;
 3 import org.apache.commons.httpclient.methods.GetMethod;
 4 import org.apache.http.Header;
 5 import org.apache.http.HttpResponse;
 6 import org.apache.http.HttpStatus;
 7 import org.apache.http.StatusLine;
 8 import org.apache.http.client.CookieStore;
 9 
10 import org.apache.http.client.HttpClient;
11 import org.apache.http.client.methods.HttpGet;
12 import org.apache.commons.httpclient.methods.GetMethod;
13 
14 import org.apache.http.client.methods.HttpPost;
15 
16 import org.apache.http.cookie.Cookie;
17 import org.apache.http.impl.client.BasicCookieStore;
18 
19 import org.apache.http.impl.client.HttpClients;
20 import org.apache.http.protocol.BasicHttpContext;
21 import org.apache.http.protocol.HttpContext;
View Code

  Pom.xml file you want to import dependence

 1        <dependency>
 2             <groupId>org.apache.httpcomponents</groupId>
 3             <artifactId>httpclient</artifactId>
 4             <version>4.5.5</version>
 5         </dependency>
 6         <dependency>
 7             <groupId>commons-httpclient</groupId>
 8             <artifactId>commons-httpclient</artifactId>
 9             <version>3.1</version>
10         </dependency>

 

1. Obtain cookie, which

getUrl (loginUrl, username, password); url is spliced, loginUrl add parameters required for splicing a login request
public String getCookies(String username, String password){
        CookieStore cookieStore = new BasicCookieStore();
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(COOKIE_STORE, cookieStore);
        HttpClient client = HttpClients.createDefault();
        String authUrl = getUrl(loginUrl, username, password);
        System.out.println("authUrl = " + authUrl);
        HttpPost post = new HttpPost(authUrl);
        try {
            response = client.execute(post, localContext);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            System.out.println("first execute code :" + statusCode);
            if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
                Header firsRedirectHeader = response.getFirstHeader("location");
                String firstRedirectUrl = firsRedirectHeader.getValue();
                HttpGet get = new HttpGet(firstRedirectUrl);
                HttpResponse getResponse = client.execute(get, localContext);
                StatusLine statusLine2 = getResponse.getStatusLine();
                int statusCode2 = statusLine2.getStatusCode();
                System.out.println("second execute code :" + statusCode2);
                System.out.println("cookie :" + cookieStore.getCookies());
                List<Cookie> cookieList = cookieStore.getCookies();
                StringBuffer tmpCookie = new StringBuffer();
                for(int i = 0 ; i < cookieList.size(); i++) {
                    tmpCookie.append(cookieList.get(i).getName()).append("=");
                    tmpCookie.append(cookieList.get(i).getValue()).append(";");
                    tmpCookie.append("domain=").append(cookieList.get(i).getDomain()).append(";");
                    tmpCookie.append("path=").append(cookieList.get(i).getPath()).append(";");
                }
                get.releaseConnection();
                return tmpCookie.toString();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(post != null){
                post.releaseConnection();
            }
        }
        return "-1";

    }
View Code

2. Get a valid cookie, we obtained after the first cookie, cookie may fail over time, so in order to bring the interface back Cookie effective, this function is also needed here to obtain a truly effective Cookie;

  public String getValidCookie(String cookie){
            if(cookie.contains("DICT_SESS")){
                return cookie;
            }else{
                Login login = new Login();
                String validCookie = login.getCookies(username, password);
                return validCookie;
            }
    }

3. real implementation of the interface code, for 2 cycles, the first is to request interface, the result is returned if the interface 403 Permission denied, call login.getValidCookie () method to log in once, get real cookie., then a second interface requests;

  If the result of the interface returns 0, the cookie is still valid, then the direct return true; which is the url parameter interface requires a real request;

 1  public Boolean executeMethod(String url) {
 2         String result = "-1";
 3         for(int i = 0; i < 2; i++) {
 4             GetMethod getMethod = new GetMethod(url);
 5             getMethod.setRequestHeader("cookie", cookie);
 6             try {
 7                 httpClient.executeMethod(getMethod);
 8                 System.out.println("method result  = " + getMethod.getResponseBodyAsString());
 9                 result = getMethod.getResponseBodyAsString();
10             } catch (IOException e) {
11                 e.printStackTrace();
12             }
13             JSONObject obj = JSONObject.parseObject(result);
14             if ("0".equals(obj.get("err").toString())) {
15                 return true;
16             }else if ("403".equals(obj.get("err").toString())) {
17                 cookie = login.getValidCookie(cookie);
18                 continue;
19             }else{
20                 return false ;
21              }
 22          }
 23          return  false ;
24  
25      }

4. When the class is loaded first log in once, save cookie, and is a global variable; when you update the cookie in step 3, you can update the variable;

   1 Login login = new Login();

2 private String cookie = login.getCookies(username, password);

3 HttpClient httpClient = new HttpClient(); 

 

Summary: The third step is to determine cookie fail to re-implement method request is not too good, hope a lot of exchanges;

Guess you like

Origin www.cnblogs.com/leavescy/p/11348733.html