你的位置:首页 > Java教程

[Java教程]有关HttpURLConnection充当代理转发Session丢失的问题

我同事最近使用甲方的专题制图的服务,在请求图片的过程中总是出现问题,最后发现原来是我们的代理(实际上是HttpURLConnection)类在转发的过程中把Session丢失,导致请求图片不成功。搞得他也蛮郁闷,甲方也很小气,不让看代码调试。

知道问题出在Session上,于是我在网上搜了一下解决方案,自己也测试了一下,解决思路如下:

1、第一次上传数据的时候,记录下SessionID(以便下次请求图片使用,而不至于session丢失s)。

2、第二次请求图片的时候,将上次记录的SessionId再传过去。

代码如下(测试代码有些粗糙):

//----------------第一次上传数据

   URL  request=new URL("http://126.33.8.251:7001/zjTMap/tTSymbolServlet?tag=config&symbolID=10&dField=%25E5%2588%25B6%25E5%259B%25BE%25E5%258C%25BA%25E5%259F%259F&cFields=%25E7%25AC%25AC%25E4%25B8%2580%25E4%25BA%25A7%25E4%25B8%259A;&rFields=%25E5%25AE%2581%25E6%25B3%25A2%25E5%25B8%2582,%25E6%259D%25AD%25E5%25B7%259E%25E5%25B8%2582&years=&dataset=%255B%257B'%25E7%25AC%25AC%25E4%25B8%2580%25E4%25BA%25A7%25E4%25B8%259A':208.41,'%25E5%2588%25B6%25E5%259B%25BE%25E5%258C%25BA%25E5%259F%259F':'%25E6%259D%25AD%25E5%25B7%259E%25E5%25B8%2582'%257D,%257B'%25E7%25AC%25AC%25E4%25B8%2580%25E4%25BA%25A7%25E4%25B8%259A':219.13,'%25E5%2588%25B6%25E5%259B%25BE%25E5%258C%25BA%25E5%259F%259F':'%25E5%25AE%2581%25E6%25B3%25A2%25E5%25B8%2582'%257D%255D&maxSize=100&minSize=16&width=80&height=80&serviceURL=%25E6%25B5%2599%25E6%25B1%259F%25E6%2594%25BF%25E5%258C%25BA/1test");		   HttpURLConnection conn=(HttpURLConnection)request.openConnection();		   conn.setRequestMethod("GET" );		   conn.setDoOutput(true );		   conn.connect();		   //		   String session_value = conn.getHeaderField("Set-Cookie" );		   String[] sessionId = session_value.split(";");		   System.out.println(sessionId[0]);		 

//----------------------第二次请求图片

 URL url =  new  URL( "http://126.33.8.251:7001/zjTMap/tTSymbolServlet?tag=image&symbolID=10&region=%25E5%25AE%2581%25E6%25B3%25A2%25E5%25B8%2582&cFields=%25E7%25AC%25AC%25E4%25B8%2580%25E4%25BA%25A7%25E4%25B8%259A;&unit=%25E6%2597%25A0&width=80&height=80&bLabel=1");		   HttpURLConnection conn2 = (HttpURLConnection)url.openConnection();		   conn2.setRequestMethod("GET" );		   conn2.setDoOutput(true );		   //第二次运行的时候,把上次读取的session的值设置上		   conn2.setRequestProperty( "Cookie", sessionId[0]);		   OutputStream fos= conn2.getOutputStream();		   IOUtil.copy(conn2.getInputStream(), new FileOutputStream("c:\\test.png"));

 代码执行完毕,跑到C盘看看,test.png打开完好。