我有一个 Java 客户端试图连接到 Express.js 网络服务器,该服务器使用 cookie 提供内容。express 服务器在浏览器上运行良好(它接收会话 cookie),但不适用于我的 Java 客户端。Java 客户端显示Set-Cookie
响应头上的字段是null
.
几乎可以肯定这是一个 Java 问题。我检查了网络流量(使用 wireshark),它显示 Express.js 网络服务器正在按预期提供 cookie。
我有以下 Java 代码:
package mine;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpsClient {
public static void main(String[] args) throws Exception {
CookieHandler.setDefault(new CookieManager());
URL obj = new URL("http://localhost:8888");
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
String headerName=null;
for (int i=1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
System.out.println(headerName + ": " + conn.getHeaderField(i));
}
}
}
上述代码的输出:
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 4535
ETag: "309029400"
Set-Cookie: null
Date: Wed, 28 Aug 2013 04:40:25 GMT
Connection: keep-alive
下面是 express.js / node.js 代码:
var express = require('express');
var app = express();
var mongoStore = require('connect-mongo')(express);
app.configure(function(){
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.errorHandler());
app.use(express.session({
store: new mongoStore({
url: 'mongodb://localhost:27017/sessions'
}),
secret: 'asdasdfasdfasdfasdfa',
maxAge : new Date(Date.now() + 24*3600*1000 * 365),
expires : new Date(Date.now() + 24*3600*1000 * 365)
}));
app.use(express.methodOverride());
});
app.get('/', function(req, res) {
res.send('ok', 200);
});
var http = require('http');
http.createServer(app).listen(8888, function(){
console.log('Express server listening on port ' + 8888);
});
我在这里错过了什么吗?Java 是否有不同的方式来处理会话 cookie?