umbrella0597
umbrella0597
2010-03-01 15:26

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

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

问题描述:

公司申请了一个超短域名,假设改域名为 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条回答

为你推荐