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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值