umbrella0597 2010-03-01 15:26
浏览 312
已采纳

寻求HttpClient无法写Cookie的解决方法

问题描述:

公司申请了一个超短域名,假设改域名为 a.cn,有多个二级域名 比如 www.a.cn; file.a.cn;这些二级域名都有一个共同的功能,
就是要写cookie,而且这个cookie要在a.cn内共享。根据短域名写cookie的可行性,只能把写Cookie的功能统一交给a.cn这台服务器来执行才可以写成功。所以我现在如果要在www.a.cn服务器上写cookie(可供a.cn共享的Cookie),就只能借助HttpClient
在a.cn服务器上有一个Servlet,用来负责写Cookie,www.a.cn这台服务器上的应用程序借助HttpClient调用a.cn上的Servlet
一切执行都没有问题,但是就是Cookie无法写入文件中。如果在IE中直接调用那个Servlet,这可以把Cookie成功写入文件。

假如Servlet的完整请求地址为 http://a.cn/servlet
a.an 服务器负责写Cookie的代码如下
[code="java"]
public class CookieServlet extends HttpServlet {

public CookieServlet() {
    super();
}


public void destroy() {
    super.destroy();        
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Cookie cookie = new Cookie("CookieName", "haha");
    cookie.setMaxAge(100000);
    cookie.setPath("/");
    //这个不需要设置
    //cookie.setDomain("a.cn");
    response.addCookie(cookie);
}

public void init() throws ServletException {

}

}
[/code]

www.a.cn的请求代码如下

[code="java"]
public class Test {

public static void main(String args[]) {
    String cookieUrl = "http://a.cn/servlet";
    String result = HttpUtils.executeGetMethod(cookieUrl);
               //其余代码省略,这里执行完后,并没有得到理想的结果。cookie没有写成功,如果
                  //在IE浏览器中执行 执行http://a.cn/servlet ,则可以成功写cookie
}

[/code]

[code="java"]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
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.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HttpUtils {
private static MultiThreadedHttpConnectionManager httpManager;
private static final Log log = LogFactory.getLog(HttpUtils.class);

public static HttpConnectionManager getHttpManager() {
    if (httpManager == null) {
        httpManager = new MultiThreadedHttpConnectionManager();
        httpManager.getParams().setConnectionTimeout(3000);
    }
    return httpManager;
}

public static HttpClient createHttpClient() {
    HttpClient client = new HttpClient(getHttpManager());       
    return client;
}

public static String executeGetMethod(String url) {
    HttpMethod method = new GetMethod(url.toString());
    return getHttpResult(method);
}

public static String executePostMethod(String url, Map<String, String> map) {
    PostMethod method = new InnerPostMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler());
    if (map == null || map.size() == 0) {
        throw new IllegalArgumentException("map must be not null");
    }
    NameValuePair[] data = new NameValuePair[map.size()];
    Set<Map.Entry<String, String>> set = map.entrySet();
    Iterator<Map.Entry<String, String>> it = set.iterator();
    int i = 0;
    while (it.hasNext()) {
        Map.Entry<String, String> entry = it.next();
        data[i++] = new NameValuePair(entry.getKey(), entry.getValue());
    }
    method.setRequestBody(data);
    return getHttpResult(method);
}

private static String getHttpResult(HttpMethod method) {
    InputStream is = null;
    try {
        HttpClient client = HttpUtils.createHttpClient();
        int stat = client.executeMethod(method);
        if (stat != HttpStatus.SC_OK) {
            return null;
        }
        is = method.getResponseBodyAsStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"));
        StringBuilder builder = new StringBuilder();
        String tmp = null;
        while ((tmp = reader.readLine()) != null) {
            builder.append(tmp);
        }

// Cookie cks[] = client.getState().getCookies();
// if (cks != null) {
// for (Cookie c : cks) {
// System.out.println(c.getName()+"\t"+c.getValue());
// }
// }
return builder.toString();
}
catch (HttpException e) {
return null;
}
catch (IOException e) {
return null;
}
finally {
method.releaseConnection();
try {
if (is != null) {
is.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}

static class InnerPostMethod extends PostMethod {
    public InnerPostMethod(String url) {
        super(url);
    }

    @Override
    protected String getContentCharSet(Header contentheader) {
        return "UTF-8";
    }
}

}
[/code]

希望有遇到过类似问题的高手,给予帮助,谢谢

  • 写回答

1条回答

  • weixin_42522104 2010-03-01 16:24
    关注

    我这有个思路,你在file.a.cn 或者 domain.a.cn 等任意二级域名的服务器网站上使用隐藏iframe来包含a.cn上写cookie的地址。
    举例:

    file.a.cn/test.do 响应的页面的内容:



    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播