Java 如何获取JSESSIONID cookie
我有一个android客户端,这就是我向tomcat服务器发出请求的方式:Java 如何获取JSESSIONID cookie,java,android,tomcat,cookies,Java,Android,Tomcat,Cookies,我有一个android客户端,这就是我向tomcat服务器发出请求的方式: protected String executeRequest(String url) { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 10000); String output = "", line = ""; try
protected String executeRequest(String url)
{
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
String output = "", line = "";
try
{
HttpGet getRequest = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try
{
getRequest = new HttpGet(url);
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200)
{
response.getStatusLine().getStatusCode();
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
while ((line = br.readLine()) != null)
{
output += line;
}
httpClient.getConnectionManager().shutdown();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.w(TAG, e.getMessage());
}
catch (IllegalStateException e)
{
e.printStackTrace();
Log.w(TAG, e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.w(TAG, e.getMessage());
}
if(output.equals(""))
{
output = null;
}
return output;
}
现在我希望能够获得JSESSIONID cookie。我知道我需要像explained一样提供cookie,但是如何在第一次获得jSessionId
谢谢 好的,我是这样做的。不知道是否有更简单的方法:
HttpResponse response = httpClient.execute(getRequest);
Header[] headers = response.getHeaders("Set-Cookie");
for(int i = 0; i < headers.length; i++)
{
if(headers[i].getName().equals("Set-Cookie"))
{
String pattern1 = "JSESSIONID=";
String pattern2 = ";";
Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
Matcher m = p.matcher(headers[i].getValue());
if(m.find())
{
sessionId = m.group(1);
break;
}
}
}
HttpResponse response=httpClient.execute(getRequest);
Header[]headers=response.getHeaders(“设置Cookie”);
对于(int i=0;i