java 에서 HTTP 클 라 이언 트 시 뮬 레이 션 로그 인 후 접근 링크

2803 단어 HTTPClient
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.UnsupportedEncodingException;

public class HTTPClientLogin {

    public static void main(String[] args) throws UnsupportedEncodingException {
        //    
        String loginUrl = "http://localhost:8080/xxx/login.do";
        //         
        String dataUrl = "http://localhost:8080/xxx/getSysMenus.do";
        JSONObject json = new JSONObject();
        json.put("username", "sys");
        json.put("password", "123456");
        HttpClientLogin(json.toString(), loginUrl, dataUrl);
    }

    private static void HttpClientLogin(String content,
                                        String loginUrl, String dataUrl) throws UnsupportedEncodingException {
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("UTF-8");
        httpClient.getParams().setHttpElementCharset("UTF-8");
        PostMethod postMethod = new PostMethod(loginUrl);
        RequestEntity requestEntity = new StringRequestEntity(content, "application/json;charse=UTF-8", "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        try {

            httpClient.getParams().setCookiePolicy(
                    CookiePolicy.BROWSER_COMPATIBILITY);
            httpClient.executeMethod(postMethod);
            Cookie[] cookies = httpClient.getState().getCookies();
            StringBuffer stringBuffer = new StringBuffer();
            for (Cookie c : cookies) {
                stringBuffer.append(c.toString() + ";");
            }

            GetMethod getMethod = new GetMethod(dataUrl);
            getMethod.setRequestHeader("Cookie", stringBuffer.toString());
            //        headers
            postMethod.setRequestHeader("Host", "localhost:8080");
            postMethod.setRequestHeader("Referer", "http://localhost:8080/xxx");
            postMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0");
            httpClient.executeMethod(getMethod);

            //       
            String result = getMethod.getResponseBodyAsString();
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

좋은 웹페이지 즐겨찾기