重用HttpURLConnection类,以保持会议还活着会议、HttpURLConnection

2023-09-05 11:03:25 作者:你结婚,我劫婚

我们有一个Android应用程序,要求用户输入一个答案的一个验证码。 验证码是我们的服务器上生成。 时的答复,它被发送到服务器进行验证

问题是,因为我要为验证码的请求之后关闭的HttpURLConnection然后我发现,答复在不同的会议上断绝运行。 正因为如此的验证码校验失败,因为它会依赖。

有没有一种方法,以保持连接活着,还是我应该遵循不同的路径? 我知道,在相当于iPhone应用程序,他们保持连接,从而具有相同的SessionID。

编辑:

  CookieManager cookieManager =新CookieManager();
    CookieHandler.setDefault(cookieManager);

    URL urlObj =新的URL(urlPath);
    康恩=(HttpURLConnection类)urlObj.openConnection();

    如果(urlPath.toLowerCase()startsWith(https:开头)){
        initializeHttpsConnection((HttpsURLConnection)康恩);
    }
    conn.setRequestMethod(POST);
    conn.setRequestProperty(内容语言,EN-US);
    conn.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
    conn.setRequestProperty(内容长度,Integer.toString(bodyData.length));
    如果(_sessionIdCookie!= NULL){
        conn.setRequestProperty(曲奇,_sessionIdCookie);
    }
    //连接
    conn.setDoInput(真正的);
    conn.setDoOutput(真正的);
    conn.connect();
 

解决方案

通常情况下,会话不基于HTTP连接本身保留。这将没有任何意义。会议通过对服务器端的客户端和会话信息的cookie通常保持活着。 你要做的是什么保存的Cookie(S)您收到,然后设置了(那些)饼干(S)下一次连接到服务器。

vivo的2018创新科技盘点,看手机市场引领者如何制胜

要了解更多关于如何使用会话和饼干用的HttpURLConnection类的工作,阅读文档:http://developer.android.com/reference/java/net/HttpURLConnection.html

下面一个小片段,让你开始:

  

要建立和维持之间的潜在的长寿命的会议   客户端和服务器,HttpURLConnection的包括一个可扩展的饼干   经理。使用的CookieHandler启用虚拟机级cookie管理,   CookieManager:

  CookieManager cookieManager =新CookieManager();
CookieHandler.setDefault(cookieManager);
 

编辑:

对于那些API级别8或更低的工作,你需要使用Apache的库!

下面是一些参考code:

  //创建cookie存储的本地实例
    CookieStore的CookieStore的=新BasicCookieStore();

    //创建本地HTTP上下文
    HttpContext的localContext =新BasicHttpContext();
    定制cookie存储//绑定到当地的情况
    localContext.setAttribute(ClientContext.COOKIE_STORE,CookieStore的);

    HTTPGET HTTPGET =新HTTPGET(http://www.google.com/);

    的System.out.println(执行请求+ httpget.getURI());

    //通过本地环境作为参数
    HTT presponse响应= httpclient.execute(HTTPGET,localContext);
 

在code以上来自Apache的库例子拍摄。它可以在这里找到: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java

编辑2: ,明确:

有关Apache的库中,你需要以某种方式与连接对象连接的cookie管理对象,你这样做,通过HttpContext对象。

在HttpURLConnection类的情况下,这是没有必要的。当您使用的CookieHandler的静态方法的 setDefault 的,你设置系统范围的CookieHandler。下面是CookieHandler.java的摘录。注意变量名(从Android开源项目的(AOSP)库):

  37 / **
 38 *设置系统级cookie处理程序。
 39 * /
 40公共静态无效setDefault(的CookieHandler钱德勒){
 41 systemWideCookieHandler =钱德勒;
 42}
 

We have an Android application that requires the user to enter an answer to a Captcha. The Captcha is generated on our server. When the replies, it is sent to the server for verifying.

Problem is that since I have to close the HttpURLConnection after the request for the Captcha I then find that the reply is running on a different session on the sever. Because of this the Captcha check fails since it is session dependant.

Is there a way to keep the connection alive or should I be following a different path? I know that in the equivalent iPhone application they remain "connected" and thus have the same sessionid.

Edit:

    CookieManager cookieManager = new CookieManager();  
    CookieHandler.setDefault(cookieManager);

    URL urlObj = new URL(urlPath);
    conn = (HttpURLConnection) urlObj.openConnection();

    if (urlPath.toLowerCase().startsWith("https:")) {
        initializeHttpsConnection((HttpsURLConnection) conn);
    }
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Language", "en-US");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", Integer.toString(bodyData.length));
    if (_sessionIdCookie != null) {
        conn.setRequestProperty("Cookie", _sessionIdCookie);
    }
    // Connect
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.connect();

解决方案

Normally, sessions are not kept based on the http connection itself. That wouldn't make any sense. Sessions are normally kept alive through a cookie on the client side and session information on the server side. What you gotta do is save the cookie(s) you're receiving and then setting that(those) cookie(s) next time you connect to the server.

To learn more about how to work with sessions and cookies with the HttpUrlConnection class, read the documentation: http://developer.android.com/reference/java/net/HttpURLConnection.html

Here a little excerpt to get you started:

To establish and maintain a potentially long-lived session between client and server, HttpURLConnection includes an extensible cookie manager. Enable VM-wide cookie management using CookieHandler and CookieManager:

CookieManager cookieManager = new CookieManager();  
CookieHandler.setDefault(cookieManager);

EDIT:

For those working with API levels 8 or lower, you'll need to use Apache's library!

Here's some reference code:

 // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Create local HTTP context
    HttpContext localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet("http://www.google.com/"); 

    System.out.println("executing request " + httpget.getURI());

    // Pass local context as a parameter
    HttpResponse response = httpclient.execute(httpget, localContext);

The code above was taken from the Apache's library examples. It can be found here: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java

EDIT 2: Making it clear:

For the Apache library you need to somehow "connect" the cookie management object with the connection object and you do that through the HttpContext object.

In HttpUrlConnection's case that's not necessary. when you use CookieHandler's static method setDefault, you're setting the system-wide cookieHandler. Below is an excerpt from CookieHandler.java. Note the variable name (from the Android Open Source Project's (AOSP) repository):

 37 /**
 38      * Sets the system-wide cookie handler.
 39      */
 40     public static void setDefault(CookieHandler cHandler) {
 41         systemWideCookieHandler = cHandler;
 42     }