HttpUrlConnection会话管理

使用HttpURLConnection类(利用sessionId保持会话

package nj.servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response){
HttpSession session=request.getSession();
String str=(String)session.getAttribute("name");
System.out.println("name:"+str);
session.setAttribute("name", "nj");
/*String ss=request.getHeader("Cookie");
System.out.println("session id:"+ss);*/
}
public void doGet(HttpServletRequest request,HttpServletResponse response){
this.doPost(request, response);
}
}

TestServlet.java
package nj.ws.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TestConnection {

public static void main(String[] args){
//第一次连接,返回session id
String sessionId=testUrlConnection();
//第二次使用session id连接
connectionBySession(sessionId);
}

public static String testUrlConnection(){
String urlStr="Http://localhost:8080/WebServiceProject/testServlet";
OutputStream out=null;
InputStream in=null;
try {
URL url=new URL(urlStr);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");

//打印请求头信息
Map hfs=con.getHeaderFields();
Set<String> keys=hfs.keySet();
for(String str:keys){
List<String> vs=(List)hfs.get(str);
System.out.print(str+":");
for(String v:vs){
System.out.print(v+"/t");
}
System.out.println();
}
System.out.println("-----------------------");
String cookieValue=con.getHeaderField("Set-Cookie");
System.out.println("cookie value:"+cookieValue);
String sessionId=cookieValue.substring(0, cookieValue.indexOf(";"));
return sessionId;
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
try {
if(in!=null)
in.close();
if(out!=null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void connectionBySession(String sessionId){
InputStream in=null;
try{
String url="Http://localhost:8080/WebServiceProject/testServlet";
URL u=new URL(url);
HttpURLConnection con=(HttpURLConnection)u.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Cookie", sessionId);
in=con.getInputStream();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(in!=null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

你可能感兴趣的:(HttpUrlConnection会话管理)