java中HTTPClient模拟登录后访问链接

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37279783/article/details/86544084
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();
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_37279783/article/details/86544084