使用Apache的HttpClient与使用JDK的URLConnection连接到applet中的URL

在下面的代码中,我已经验证了如果使用JDK的URLConnection类,从applet中连接到URL会保留浏览器的会话.但是,如果使用Apache的HttpClient库,则情况并非如此.有谁知道为什么?或者,有没有办法让我设置HttpClient实例使用的连接实例?

import java.applet.Applet;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;

import javax.net.ssl.SSLException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientTesterApplet extends Applet {
    private static final long serialVersionUID = -1599714556710568947L;

    public void testHttpClient() throws ClientProtocolException, IOException,
            URISyntaxException {
        URL url = new URL(String.format("%s://localhost:%s/%s/testHttpClient",
                getParameter("protocol"), getParameter("port"),
                getParameter("context")));

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost(url.toURI());

        System.out.println("Executing request " + post.getURI());

        try {
            System.out
                    .println(client.execute(post, new BasicResponseHandler()));
        } catch (SSLException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Executed request " + post.getURI());

        System.out.println("Opening connection " + url);

        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();

        System.out.println("Opened connection " + url);

        urlConnection.setRequestMethod("POST");

        System.out.println("Connecting");

        urlConnection.connect();

        System.out.println("Connected");

        InputStream inputStream = urlConnection.getInputStream();

        try {
            while (inputStream.read() != -1) {
                System.out.println("Reading");
            }
        } finally {
            inputStream.close();
        }
    }
}

解决方法:

这是库通过Socket实现自己的URL连接的常见问题.显然,URLConnection类的JRE实现可以直接获取浏览器信息.我们必须使用上面oscargm提到的技术,即在appserver上写请求cookie作为applet的参数并使用JavaScript获取浏览器的文档cookie(这适用于SSO的情况,其中cookie集可能因为中间代理 – 代理服务器而不一样.请注意,如果cookie是HttpOnly – javascript代码将失败.

上一篇:[AtCoder Beginner Contest 133]F - Colorful Tree


下一篇:Java applet与硬件加速3D图形? OpenGL和/或DirectX