验证码是在我们的服务器上生成的.
当回复时,它被发送到服务器进行验证.
问题是,由于我必须在请求Captcha I之后关闭HttpURLConnection,所以我发现回复正在服务器上的不同会话上运行.
因为这样,验证码检查失败,因为它是会话依赖的.
有没有办法保持连接活着或应该跟随不同的路径?
我知道在相同的iPhone应用程序中,它们保持“连接”,因此具有相同的sessionid.
编辑:
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();
解决方法
你要做的是保存你正在接收的cookie,然后在连接到服务器时设置(那些)cookie.
要了解有关如何使用HttpUrlConnection类使用会话和Cookie的更多信息,请阅读以下文档:http://developer.android.com/reference/java/net/HttpURLConnection.html
这里有一点摘录让你开始:
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);
编辑:
对于那些使用API级别为8或更低版本的用户,您需要使用Apache的库!
以下是一些参考代码:
// 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);
上面的代码是从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 * Sets the system-wide cookie handler. 39 */ 40 public static void setDefault(CookieHandler cHandler) { 41 systemWideCookieHandler = cHandler; 42 }