HttpClient模拟请求登录的jSessionId无法手动修改的问题

原因: 当jSessionId失效(发生改变)时必须重新new一个HttpClient

代码

import com.cotton.util.NumberUtil;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    private static Logger logger = Logger.getLogger(HttpClientUtil.class);

    private static HttpClient client = null;

    private static String theJSessionId;

    public static String post(String url, String[] proxy, String jSessionId, Map<String, String> params) throws Exception {


        if (!StringUtils.equals(theJSessionId, jSessionId)) {
            logger.warn("new HttpClient");
            client = new HttpClient();
            theJSessionId = jSessionId;
        }

        String content = "error";

        PostMethod post = new PostMethod(url);
        List<Header> headers = new ArrayList<Header>();
        headers.add(new Header("Cookie", "JSESSIONID=" + jSessionId));

        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);

        NameValuePair[] pairs = new NameValuePair[params.size()];

        int i = 0;
        for (Map.Entry<String, String> en : params.entrySet()) {
            pairs[i] = new NameValuePair(en.getKey(), en.getValue());
            i++;
        }

        post.addParameters(pairs);

        if (proxy != null && proxy.length == 2) {
            client.getHostConfiguration().setProxy(proxy[0], NumberUtil.toInt(proxy[1]));
        }
        int code = client.executeMethod(post);


        if (code == 200) {
            content = post.getResponseBodyAsString();
        }

        return content;
    }
}



猜你喜欢

转载自blog.csdn.net/zyf_balance/article/details/77992146
今日推荐