我正在尝试创建一个向服务器发送一些 POST 请求的 Java 应用程序。第一个请求是带有身份验证信息的请求。然后,当我发送下一个请求时,我得到的答案是我的会话已过期。但我在同一秒内发送下一个请求,所以它不能超时。
所以我猜想 Java 中有类似 HTTP 会话的东西,我需要用它来发送我的请求,这样服务器就知道它遵循前一个请求。
我一直在谷歌搜索,但找不到任何东西。只是一些关于 Servlet 的内容。但我正在创建一个桌面应用程序。
PS:我对发送 HTTP 请求和此类事情还不熟悉。
提前致谢,
Martijn
编辑:这是我当前使用的代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author martijn
*/
public class PostRequest {
private String _url;
private List<PostParameter> params;
public PostRequest(String url) {
this._url = url;
this.params = new ArrayList<PostParameter>();
}
public void addParam(String key, String value)
{
params.add(new PostParameter(key, value));
}
public String getURL()
{
return _url;
}
public InputStream request() throws IOException {
URL url = new URL(this._url);
URLConnection conn = url.openConnection();
if (params.size() > 0) {
conn.setDoOutput(true);
StringBuilder data = new StringBuilder();
for (int i = 0; i < params.size(); i++) {
if (i > 0) {
data.append("&");
}
String key = params.get(i).key;
String value = params.get(i).value;
data.append(URLEncoder.encode(key, "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(value, "UTF-8"));
}
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data.toString());
wr.flush();
}
return conn.getInputStream();
}
public class PostParameter {
public String key;
public String value;
public PostParameter(String key, String value) {
this.key = key;
this.value = value;
}
public PostParameter() {
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
public void setKey(String key) {
this.key = key;
}
public void setValue(String value) {
this.value = value;
}
}
}
然后依次发送两个请求:
PostRequest postAuthentication = new PostRequest("http://blahblah.com");
postAuthentication.addParam("user", user);
postAuthentication.addParam("password", pass);
Utils.dumpReader(postAuthentication.request());
PostRequest postDoSomething = new PostRequest("http://blahblah.com/function.php");
postDoSomething.addParam("func", "blah");
postDoSomething.addParam("value", "14");
Utils.dumpReader(postDoSomething.request());
// Here I'm getting the session is expired.