I'm trying to make a Java application that sends some POST requests to a server. The first request is the one with authentication information. Then when I send the next request, I'm getting the answer that my session is expired. But I'm sending the next request within the same second, so, it can't be timed out.
So I guess there is something like a HTTP Session in Java, which I need to use for sending my request that way the server knows its following the previous request.
I've been searching Google, but can't find anything. Only something about Servlets. But I'm creating a desktop application.
PS: I'm new to sending HTTP requests and this kind of things.
Thanks in advance,
Martijn
Edit: This is the code I use currently:
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;
}
}
}
And then send two request after each other:
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.