Amy*_*ips 10 cookies android httprequest android-webview
我发送cookie作为http get的一部分时遇到问题.首先,我进入webview中的登录页面,它给了我一个cookie.我检查过,cookie存储在CookieManager中.然后我使用BasicHttpRequest从同一个域获取特定的URL.我希望我从登录中获得的cookie可以附加到我的头文件中获取,但是在Wireshark中查看它并不存在.我用Google搜索并阅读了很多类似的问题,并确保:
我在webview中启动登录页面的代码如下所示:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// use cookies to remember a logged in status
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
//not sure if I need to do this
CookieManager cookie_manager = CookieManager.getInstance();
cookie_manager.setAcceptCookie(true);
webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new HelloWebViewClient()); // if user clicks on a url we need to steal that click, also steal the back button
webview.loadUrl("http://"+my_server+"/api/v1/login");
setContentView(webview);
Run Code Online (Sandbox Code Playgroud)
然后我检查cookie的代码看起来像:
public static boolean CheckAuthorised() {
CookieSyncManager.getInstance().sync();
CookieManager cookie_manager = CookieManager.getInstance();
String cookie_string = cookie_manager.getCookie("http://"+my_server+"/api/v1/login");
System.out.println("lbp.me cookie_string: " + cookie_string);
if(cookie_string != null)
{
String[] cookies = cookie_string.split(";");
for (String cookie : cookies)
{
if(cookie.matches("API_AUTH=.*"))
{
// maybe we need to store the cookie for the root of the domain?
cookie_manager.setCookie("http://"+my_server, cookie_string);
// maybe we need to store the cookie for the url we're actually going to access?
cookie_manager.setCookie("http://"+my_server+"/api/v1/activity", cookie_string);
CookieSyncManager.getInstance().sync();
return true;
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
而实际上我做的http请求
public static HttpResponse getMeAWebpage(String host_string, int port, String url)
throws Exception {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
// HttpHost host = new HttpHost("www.svd.se", 80);
HttpHost host = new HttpHost(host_string, port);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
//CookieManager cookie_manager = CookieManager.getInstance();
//CookieStore cookie_store = cookie_manager.getCookieStore(); //The method getCookieStore() is undefined for the type CookieManager
//context.setAttribute(ClientContext.COOKIE_STORE, cookie_store);
HttpResponse response = null;
try {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", url);
System.out.println(">> Request URI: "
+ request.getRequestLine().getUri());
System.out.println(">> Request: "
+ request.getRequestLine());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
String ret = EntityUtils.toString(response.getEntity());
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(ret);
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
} catch(UnknownHostException e) {
System.out.println("UnknownHostException");
} catch (HttpException e) {
System.out.println("HttpException");
} finally {
conn.close();
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
感谢您阅读这篇文章!感激地收到任何建议,
艾米
附加cookies终于对我有用了!我可能没有用最简单的方法做到这一点,但至少它有效。我的重大突破是下载并附加 Android 源代码,这样我就可以逐步查看发生了什么。这里有说明http://blog.michael-forster.de/2008/12/view-android-source-code-in-eclipse.html - 向下滚动并阅读 Volure 的评论以获得最简单的下载。如果您在 Android 上进行开发,我强烈建议您这样做。
现在讨论工作cookie代码 - 大多数更改都在实际获取我的网页的代码中 - 我必须设置一个COOKIE_STORE和一个COOKIESPEC_REGISTRY。然后我还必须更改我的连接类型,因为 cookie 代码将其转换为 ManagedClientConnection:
public static HttpResponse getMeAWebpage(String host_string, int port, String url)
throws Exception {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
//params.setParameter("cookie", cookie);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
httpproc.addInterceptor(new RequestAddCookies());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
// HttpHost host = new HttpHost("www.svd.se", 80);
HttpHost host = new HttpHost(host_string, port);
HttpRoute route = new HttpRoute(host, null, false);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
SingleClientConnManager conn_mgr = new SingleClientConnManager(params, schemeRegistry);
ManagedClientConnection conn = conn_mgr.getConnection(route, null /*state*/);
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
CookieStore cookie_store = new BasicCookieStore();
cookie_store.addCookie(cookie);
context.setAttribute(ClientContext.COOKIE_STORE, cookie_store);
// not sure if I need to add all these specs, but may as well
CookieSpecRegistry cookie_spec_registry = new CookieSpecRegistry();
cookie_spec_registry.register(
CookiePolicy.BEST_MATCH,
new BestMatchSpecFactory());
cookie_spec_registry.register(
CookiePolicy.BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory());
cookie_spec_registry.register(
CookiePolicy.NETSCAPE,
new NetscapeDraftSpecFactory());
cookie_spec_registry.register(
CookiePolicy.RFC_2109,
new RFC2109SpecFactory());
cookie_spec_registry.register(
CookiePolicy.RFC_2965,
new RFC2965SpecFactory());
//cookie_spec_registry.register(
// CookiePolicy.IGNORE_COOKIES,
// new IgnoreSpecFactory());
context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, cookie_spec_registry);
HttpResponse response = null;
try {
if (!conn.isOpen()) {
conn.open(route, context, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", url);
System.out.println(">> Request URI: "
+ request.getRequestLine().getUri());
System.out.println(">> Request: "
+ request.getRequestLine());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
String ret = EntityUtils.toString(response.getEntity());
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(ret);
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
} catch(UnknownHostException e) {
System.out.println("UnknownHostException");
} catch (HttpException e) {
System.out.println("HttpException");
} finally {
conn.close();
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
我设置 cookie 的代码与 getMeAWebpage() 位于同一类中,如下所示:
public static void SetCookie(String auth_cookie, String domain)
{
String[] cookie_bits = auth_cookie.split("=");
cookie = new BasicClientCookie(cookie_bits[0], cookie_bits[1]);
cookie.setDomain(domain); // domain must not have 'http://' on the front
cookie.setComment("put a comment here if you like describing your cookie");
//cookie.setPath("/blah"); I don't need to set the path - I want the cookie to apply to everything in my domain
//cookie.setVersion(1); I don't set the version so that I get less strict checking for cookie matches and am more likely to actually get the cookie into the header! Might want to play with this when you've got it working...
}
Run Code Online (Sandbox Code Playgroud)
如果您遇到类似的问题,我真的希望这对您有所帮助 - 我感觉我已经用头撞墙好几个星期了!现在来一杯当之无愧的庆祝茶吧:o)
归档时间: |
|
查看次数: |
4750 次 |
最近记录: |