`
deaboway
  • 浏览: 54184 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多

Java代码
  1. public InputStreamgetStream(URLurl,Stringpost,URLcookieurl){
  2. HttpURLConnectionconnection;
  3. StringcookieVal=null ;
  4. StringsessionId="" ;
  5. Stringkey=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. InputStreamin=connection.getInputStream();
  17. System.out.println(sessionId);
  18. }catch (MalformedURLExceptione){
  19. System.out.println("urlcan'tconnection" );
  20. return null ;
  21. }catch (IOExceptione){
  22. System.out.println(e.getMessage());
  23. return null ;
  24. }
  25. }
  26. try {
  27. connection=(HttpURLConnection)url.openConnection();
  28. //这个要写在Post前,否则会取不到值,原因我不知道
  29. if (cookieurl!= null ){
  30. connection.setRequestProperty("Cookie" ,sessionId);
  31. }
  32. if (post!= "" ){
  33. connection.setDoOutput(true );
  34. connection.setRequestMethod("POST" );
  35. connection.getOutputStream().write(post.getBytes());
  36. connection.getOutputStream().flush();
  37. connection.getOutputStream().close();
  38. }
  39. int responseCode=connection.getResponseCode();
  40. int contentLength=connection.getContentLength();
  41. //System.out.println("Contentlength:"+contentLength);
  42. if (responseCode!=HttpURLConnection.HTTP_OK) return ( null );
  43. InputStreamin=connection.getInputStream();
  44. return (in);
  45. }
  46. catch (Exceptione){
  47. //System.out.println(e);
  48. //e.printStackTrace();
  49. return ( null );
  50. }
  51. }

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics