我正在嘗試製作將某些POST請求發送到服務器的Java應用程序。第一個請求是具有認證信息的請求。然後,當我發送下一個請求時,我收到了會話過期的答案。但是我在同一秒內發送下一個請求,所以它不能超時。Java:如何進行HTTP瀏覽會話
所以我猜想有一些東西就像Java中的HTTP會話,我需要用它來發送我的請求,服務器知道它遵循先前的請求。
我一直在搜索谷歌,但找不到任何東西。只有一些關於Servlets。但我正在創建一個桌面應用程序。
PS:我是新來發送HTTP請求和這種事情。
由於提前,
馬亭
編輯:這是我的代碼目前使用:
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.
你有一小段相關的**代碼嗎? – Thor 2011-06-10 12:23:32