java httpurlconnection 发送cookie时,cookie要在Post前发送

 
  1. public InputStream getStream(URL url,String post,URL cookieurl){   
  2.         HttpURLConnection connection;   
  3.         String cookieVal = null;   
  4.         String sessionId = "";   
  5.         String key=null;   
  6.         if(cookieurl!=null){               
  7.             try{   
  8.                 connection = (HttpURLConnection)cookieurl.openConnection();   
  9.                 for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++ ) {   
  10.                     if (key.equalsIgnoreCase("set-cookie")) {   
  11.                         cookieVal = connection.getHeaderField(i);   
  12.                         cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));   
  13.                         sessionId = sessionId+cookieVal+";";   
  14.                     }   
  15.                 }   
  16.                 InputStream in = connection.getInputStream();   
  17.                 System.out.println(sessionId);   
  18.             }catch(MalformedURLException e){   
  19.                 System.out.println("url can't connection");   
  20.                 return null;   
  21.             }catch(IOException e){   
  22.                 System.out.println(e.getMessage());   
  23.                 return null;   
  24.             }   
  25.         }   
  26.   
  27.         try {   
  28.             connection = (HttpURLConnection)url.openConnection();   
  29.             //这个要写在Post前,否则会取不到值,原因我不知道   
  30.             if(cookieurl!=null){   
  31.                 connection.setRequestProperty("Cookie", sessionId);   
  32.             }   
  33.             if(post!=""){   
  34.                 connection.setDoOutput(true);   
  35.                 connection.setRequestMethod("POST");   
  36.                 connection.getOutputStream().write(post.getBytes());   
  37.                 connection.getOutputStream().flush();   
  38.                 connection.getOutputStream().close();   
  39.             }   
  40.             int responseCode = connection.getResponseCode();   
  41.             int contentLength = connection.getContentLength();   
  42.             // System.out.println("Content length: "+contentLength);   
  43.             if (responseCode != HttpURLConnection.HTTP_OK ) return(null);   
  44.             InputStream in = connection.getInputStream();   
  45.             return(in);   
  46.         }   
  47.         catch(Exception e) {   
  48.             // System.out.println(e);   
  49.             // e.printStackTrace();   
  50.             return(null);   
  51.         }   
  52.            
  53.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值