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



Java代码 
  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 1(key connection.getHeaderFieldKey(i)) != nulli++  
  10.                     if (key.equalsIgnoreCase(“set-cookie”))  
  11.                         cookieVal connection.getHeaderField(i);  
  12.                         cookieVal cookieVal.substring(0cookieVal.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.      

转自:http://stephenjqj.javaeye.com/blog/477194

欢迎关注我的微信公众号:

 

如无特殊说明,文章均为本站原创,转载请注明出处!

发表回复

您的电子邮箱地址不会被公开。