HttpClient 시 뮬 레이 션 로그 인, 세 션 유지 및 후속 작업

2901 단어 자바
package cc.unmi.httpclient; 
 
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
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;
import org.junit.Test;
 
public class HttpClientLogin {
 
    public static void main(String[] args){
        //   Url
        String loginUrl = "http://localhost/unmi/login.html";
 
        //        Url
        String dataUrl = "http://localhost/unmi/user_info.html?userid=123456";
 
        HttpClient httpClient = new HttpClient();
 
        //    ,            Post   Get     
        PostMethod postMethod = new PostMethod(loginUrl);
 
        //          ,         ,        
        NameValuePair[] data = {
                new NameValuePair("username", "Unmi"),
                new NameValuePair("password", "123456"),
                new NameValuePair("code", "anyany")
        };
        postMethod.setRequestBody(data);
 
        try {
            //   HttpClient    Cookie,          
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            httpClient.executeMethod(postMethod);
 
            //       Cookie
            Cookie[] cookies=httpClient.getState().getCookies();
            String tmpcookies= "";
            for(Cookie c:cookies){
                tmpcookies += c.toString()+";";
            }
 
            //        
            GetMethod getMethod = new GetMethod(dataUrl);
 
            //                  cookie      
            getMethod.setRequestHeader("cookie",tmpcookies);
 
            //       PostMethod/GetMethod           
            //  ,referer      ,UA              ,        
            postMethod.setRequestHeader("Referer", "http://unmi.cc");
            postMethod.setRequestHeader("User-Agent","Unmi Spot");
 
            httpClient.executeMethod(getMethod);
 
            //       ,        
            String text = getMethod.getResponseBodyAsString();
            System.out.println(text);
 
        } catch (Exception e) {
            e.printStackTrace();
        }   
    }
}

Basic 인증 의 간단 한 코드 가이드, 아직 직접 시도 하지 않 았 습 니 다:
HttpClient client = new HttpClient();
 
// 1
client.getState().setCredentials(
    new AuthScope("unmi.cc", 80, AuthScope.ANY_REALM),
    new UsernamePasswordCredentials("username", "password")
);
 
// 2
client.getParams().setAuthenticationPreemptive(true);
 
// 3
GetMethod getMothod = new GetMethod("http://unmi.cc/twitter");
 
// 4
getMothod.setDoAuthentication( true );
 
// 5
int status = client.executeMethod( getMothod );

좋은 웹페이지 즐겨찾기