gpt4 book ai didi

java - HTTPclient 和 cookie 的问题

转载 作者:行者123 更新时间:2023-12-01 05:25:13 24 4
gpt4 key购买 nike

我目前正在开发一个移动应用程序,该应用程序将通过 HTTP 协议(protocol)与 RESTfull 服务器进行通信。为此,我编写了一个工作代码并实现了通信。

为了让服务器识别用户,我想使用 cookie(某种 session cookie)。因此,我开始使用以下两个辅助方法来创建 HttpClient 和上下文(包括我的 cookie)。

// Gets a standard client - set to HTTP1.1
private HttpClient getClient() {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
return new DefaultHttpClient(params);
}

// Gets the context with cookies to be used. This is to make each user unique
private HttpContext getHttpContext(String server) {
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("X-ANDROID-USER", "some name");
cookie.setDomain(server);
cookie.setPath("/");
cookie.setVersion(1);

cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
return localContext;
}

然后我使用以下命令连接到服务器(读取功能)。这基本上采用最后两个辅助方法生成的 Client 和 Conext 并执行正常的 GET 请求。
//连接restfull服务器并返回返回值(get请求)



<pre> private String restfullRead(URI uri, String server)
{
// Sets up the different objects needed to read a HttpRequest
HttpClient client = this.getClient();
HttpGet request = new HttpGet();
request.setURI(uri);
HttpContext context = this.getHttpContext(server);

// Connects to the server and reads response
try {
HttpResponse response = client.execute(request, context);
reader.close();
}
catch (Exception e) {
return "";
}</pre>

When I run this to my server I get the following request.<br/>
GET /info/1 HTTP/1.1<br/>
Host: 192.168.0.191:8080<br/>
Connection: Keep-Alive

如您所见,这不包含任何 cookie。这就是为什么我想知道,为什么“getHttpContext”中制作的cookie没有在请求中发送?

最佳答案

这个答案会对您有所帮助:

How do I make an http request using cookies on Android?

//编辑

1.) 您的 Android 应用程序将其唯一的 NFC 标签发送到服务器。

2.) 服务器创建一个新的唯一 token 并在 token 和 NFC 标签之间建立关系

3.) 每当您的应用程序发送请求时,也发送唯一的 NFC 标签。

4.) 服务器将检查 NFC 标签并搜索 token ,现在您的设备已被识别

发送自定义 header :

HttpGet get = new HttpGet(getURL);
get.addHeader("NFC", "YOUR NFC-TAG");
get.addHeader("Some more header", "more infos");

关于java - HTTPclient 和 cookie 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9789939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com