HttpClient 는 로그 인 쿠키 상 태 를 유지 하고 계속 작 동 합 니 다.

5801 단어 자바
        import org.apache.commons.httpclient.Cookie;
        import org.apache.commons.httpclient.HttpClient;
        import org.apache.commons.httpclient.HttpException;
        import org.apache.commons.httpclient.NameValuePair;
        import org.apache.commons.httpclient.cookie.CookiePolicy;
        import org.apache.commons.httpclient.methods.GetMethod;
        import org.apache.commons.httpclient.methods.PostMethod;

        HttpClient httpClient = new HttpClient();

        //     ,            Post   Get     
        PostMethod postMethod = new PostMethod("http://123.com");

        //           ,         ,        
        NameValuePair[] data = { new NameValuePair("username", "20169065"),
                new NameValuePair("password", "Q123123q")

        };
        postMethod.setRequestBody(data);
        String tmpcookies = "";
        try {
            //    HttpClient    Cookie,          
            httpClient.getParams().setCookiePolicy(
                    CookiePolicy.BROWSER_COMPATIBILITY);
            httpClient.executeMethod(postMethod);

            //        Cookie
            Cookie[] cookies = httpClient.getState().getCookies();
            tmpcookies = "";
            for (Cookie c : cookies) {
                tmpcookies += c.toString() + ";";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("    :" + loginUrl);
        System.out.println("       :" + "20169065");
        System.out.println("      :" + "Q123123q");
        ------------------------------------------------------------
        GetMethod getMethod = new GetMethod("http://123.com");
        getMethod.setRequestHeader("Cookie", tmpcookies);
        //   ,referer      ,UA              ,        
        postMethod.setRequestHeader("Referer", "http://123.com");
        postMethod.setRequestHeader("User-Agent", "Unmi Spot");
        httpClient.executeMethod(getMethod);
        System.out.println(getMethod.getResponseBodyAsString());;

좋은 웹페이지 즐겨찾기