At the beginning i was sending a redirect with the cookies set on HttpServletResponse but later i decided to not redirect and only get the information gave from the servlet but the problem is i can't set the cookies on this post method.
So i would like to know how to set cookies with postmethod and if there is a way to process the cookies that are in HttpServletResponse
String temp=null;
HttpClient client = new HttpClient();
client.getParams().setParameter("http.useragent", "Oauth Data Requester");
BufferedReader br = null;
PostMethod method = new PostMethod(ADDRESS+"/SampleProvider");
//Aqui ainda enviamos o XML inteiro como parametro
method.addParameter("p", "\"java2s\"");
try{
int returnCode = client.executeMethod(method);
if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("no post method found");
} else {
temp=method.getResponseBodyAsString();
}
} catch (Exception e) {
System.err.println(e);
} finally {
开发者_StackOverflow method.releaseConnection();
if(br != null) try { br.close(); } catch (Exception e) {}
}
return temp;
}
In servlets, you can get all cookies sent by the client using HttpServletRequest#getCookies()
.
Cookie[] cookies = request.getCookies();
// ...
And you can set cookies on the response using HttpServletResponse#addCookie()
.
response.addCookie(new Cookie(name, value));
In HttpClient 3.x (I assume that you're using 3.x, because the executeMethod()
method isn't present on 4.x anymore), you can add cookies to the HttpState
and then set it on HttpClient
before executing the method.
HttpState state = new HttpState();
state.addCookie(new Cookie(".example.com", "name", "value"));
HttpClient client = new HttpClient();
client.setState(state);
// ...
After executing the method, you can get the (updated) cookies by
Cookie[] cookies = client.getState().getCookies();
// ...
精彩评论