HttpURLConnection and valid cookies

Hi,
I have implemented a web server with a login page to authenticate a user.
When the browser has not send a valid cookie, the server redirects to the
login page, where the user can fill a form to post the username and password.
I am implementing a java stand-alone client to access this web server. I use
the HttpURLConnection class for this.
First, i authenticate the user sending a post request with the login and
password. The server responds with a cookie. To access other resources in
the server i send the cookie in each request.
My problem is: i am using java class HttpURLConnection. When the cookie
is not valid, the server redirects to the login page, but i have not
found a way to know about it without parsing the response html. I get the http
header fields but there is no info about this.
Thanks in advance

You should extraxt the sessionID from the cookie, when logging on to the system.
From then on, pass the session ID to all further connections.
You can obtain the session-ID like this:
public void retrieveSessionID() {
               String key = "";
               String id = "";
               try {
                 URL url = new URL ( "http://localhost/yourapplication/logon.jsp?username=Homer&password=donut);
                 URLConnection urlConnection = url.openConnection();
                 if (urlConnection != null)
                      for (int i = 1;(key = urlConnection.getHeaderFieldKey(i)) != null; i++)
                           if (key.equalsIgnoreCase("set-cookie"))
                                id = urlConnection.getHeaderField(key);
                                id = id.substring(0, id.indexOf(";"));
                           }     //if
                      }     //for
                 }     //if
               } catch (IOException e) {
                                                                      e.printStackTrace();
               }     //catch
                 this.jSessionId = id;
     }     //getSessionIDAnd then make every connection like this:
URL url = new URL("http:......");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.setRequestProperty("Cookie", this.jSessionId);
                connection.connect();                Hope I could help!
Greetings
Stef

Similar Messages

  • Problem with HttpURLConnection and HttpSession.

    Hi,
    Problem with HttpURLConnection and HttpSession.
    I created a HttpSession object in my main class and then called a URL via HttpURLConnection.
    I tried to access the same session object from the servlet called by the URL . but the main session
    is not returned a new seperate session is created.let me know how can we continue the same session in
    the called URL also which is created in main class.
    Thanks
    Prasad

    You are not supported to create a HttpSession by java client. Only J2EE web container can create it.

  • How to know the balance and validity of internet data in iPad

    How to know the balance and validity of internet data in iPad?

    Sir I m using internet in ipad4 with airtel network
    They provide me 2gb data with the amount of 255 rupees
    And now I inserted the sim in my ipad4
    And start the surfing on safari n all
    And now I wanted to know how much data is balance.

  • Need help. I am running a 27 in imac with 16 gigs of ram. Photoshop runs really fast, except when opening files. It takes 5-10 minutes to open even a small file of 1 meg. I cleaned and validated all the fonts and removed all questionable fonts. Reset pref

    Need help. I am running a 27 in imac with 16 gigs of ram. Photoshop runs really fast, except when opening files. It takes 5-10 minutes to open even a small file of 1 meg. I cleaned and validated all the fonts and removed all questionable fonts. Reset preferences and still have problem. Slow to open and in force quit "Photoshop not responding" At this point should I uninstall and start over.

    What are the performance Preferences?

  • How to Use the language function for assignment and validation

    Hi All,
    If anyone can explain me in details with example ,how to use the language function for assignments and validations?
    Thanks
    Arnab

    Hi Arnab,
    The expression is checked only for the current MDM session.
    If u login with the ABC language it will always show the ABC language no matter how many times u execute it.
    Try connecting to the DM with the XYZ language.
    It should go to the if part rather than else.
    Hope it helps.
    Thanks,
    Minaz

  • How to get the latest and valid BOM item entry from STPO

    hi,
    may i know with what condition we can get the latest and valid BOM item entry from STPO table?
    i have STLNR and IDNRK as a input. But i realized that it would return multiple entry due to the combination of  valid-from and valid till date.
    can i use stlnr,idnrk and stpoz (with the latet counter) to get the latest and valid BOM entry?
    thank you.

    Hi
    You can get the latest BOM either by using the latest valid from date DATUV or latest internal counter STPOZ
    Regards
    Shiva

  • Difference between "Binding Period" and "Validity Start/End" in Bid

    SRM Experts,
    1. We see 2 different things, "Binding Period" and "Validity Start/End" while preparing the bid. What is the differece between these?
    2. These fileds are non-editable for the bidder, while preparing the bid response. How bidder can give validity period for his quote (at header level)?
    3. We see that, the bidder can specify validity start/end date at condition level. Is it not possible to specifiy a validity of the quote at header level?
    GH

    case1: After expiration of  - binding period in RFx header:
    case2: After expiration of  - validity end period in RFx header:
    case3: After expiration of  - validity end period of RFx Response:
    I created seprate documents for each cases.
    I tried accepting the RFx response in all above 3 cases system did not give any error.
    I tried creating the PO against the RFx response in all above 3 cases system did not give any error.
    Is it correct behavior or is there any problem?
    GH

  • Help with Conditional Display and Validation

    Version 4.1.1.00.23
    Hello,
    I'm having a difficult time with a conditional display and validation I'm hoping someone can help with.
    Requirements:
    When the Start Date (Datepicker) and/or End Date (Datepicker) change then display the Change Reason (Select List) and Change Description (Textbox)
    If the page is saved without entering a Change Reason display a validation error message that the Change Reason cannot be empty (NULL)
    What I've tried
    Create a Dynamic Action on the Start Date
    Event: Change
    Selection Type:Item(s)
    Items(s): P51_START_DATE
    Condition: none
    True Action Section:
    Action: Show
    Fire on Page Load: Checked
    Show all page items on the same line: No
    Affected Items Section:
    Selection Type:Item(s)
    Item(s): P51_CHANGE_REASON,P51_CHANGE_DESC
    I've also created a Dynamic Action with similar settings for the P51_END_DATE.
    I created a Validation for the P51_CHANGE_REASON as Function Returning Error Text:
    DECLARE
        v_start_date    work_items.start_date%TYPE;
        v_end_date      work_items.end_date%TYPE;
    BEGIN
        SELECT start_date
              ,end_date
        INTO   v_start_date
              ,v_end_date
        FROM   work_items
        WHERE  work_items_id = :P51_WORK_ITEMS_ID;
        IF ( (v_start_date != TO_DATE(:P51_START_DATE,'DD-MON-YYYY') OR v_end_date != TO_DATE(:P51_END_DATE,'DD-MON-YYYY') ) AND
              :P51_CHANGE_REASON IS NULL ) THEN
            RETURN 'Change Reason must have a value';
        END IF;
    END;
    The Issue
    I tried to create another Dynamic Action to hide the P51_CHANGE_REASON and P51_CHANGE_DESC fields on page load, but when either of the date fields are changed and the validation is fired the P51_CHANGE_REASON and P51_CHANGE_DESC are hidden again.
    There are two buttons to submit the page: 'SAVE' will submit the page and stay on the page and 'SAVE_CHANGES' will submit the page and branch to the previous page (which is a report with EDIT buttons to edit the record).
    I can't get the page load Dynamic Action to NOT fire when the validation is fired.
    I hope this is clear and if not what information can I provide?
    Thanks,
    Joe

    Phil,
    Thank you for looking at this.
    Yes if the Change Reason is NULL when the edit page is displayed then the Change Reason and Change Description fields are hidden. If the Start Date (Datepicker) and/or End Date (Datepicker) change then display the Change Reason (Select List) and Change Description (Textbox). If the page is saved without entering a Change Reason display a validation error message that the Change Reason cannot be empty (NULL).
    The problem I'm having is that if no Change Reason is entered and the page is saved thereby firing the validation the Change Reason and Change Description fields are hidden again (because of the On-Load Dynamic Action to hide them). So now the user can't put in a Change Reason...unless they change one of the date fields again which isn't going to be accepted.
    Is there a way to determine if a validation error was fired and be able to use that on the On-Load Dynamic Action to hide the two fields? Something like...If the validation fired then don't run?
    Please let me know if I'm still confusing you.
    Thanks,
    Joe

  • Name of the table where can get the two fields Valid-From and Valid-to for

    Hi gurus
    I want name of the table where I can get the two fields Valid-From and Valid-To and their relation ship with the header table in BOM
    Regards
    Kaisar

    You can only get the Valid from date from the table STKO.
    To get the valid to date, you have to take one day less than the valid-from date of the next record for the same BOM.
    Alternatively use the Function module:
    CSAP_MAT_BOM_READ
    It will give both valid from and valid to dates in the tables parameter: T_STKO
    Regards,
    Ravi
    Edited by: Ravi Kanth Talagana on Jul 2, 2008 4:37 PM

  • File Browse Item and validation

    Hello
    I have a page with multiple items and validations.
    One of the items is "File Browse..."
    When I select a file on my computer and submit the page, a new record is created in "APEX_APPLICATION_FILES".
    In the page I have a process that saves the blob from "APEX_APPLICATION_FILES" into one of my DB table and then I delete that record.
    That is correct.
    But, if one of my validations is triggered, the record is still created in "APEX_APPLICATION_FILES" and since the validation blocks the execution of my process, the record is not deleted.
    Normally, it should be deleted to prevent the table from taking too much space.
    Is there any DB Job that "cleans" the table?
    Thank you
    Max

    Hi
    I just tough I could do the following validation as the very last one.
    Validation type:
    "Function returning error text"
    Validation Expression:
    begin
       delete from APEX_APPLICATION_FILES
       where name = :P1_MY_BROWSE_ITEM;
       return null;
    end;Condition :
    "Inline validation errors displayed"
    Is there a "cleaner" or better solution I should use ?
    Thanks
    Max

  • I have tried all the steps you listed in your FAQ sextion on enabling and disabling cookies but I am still getting the error message "cookies not enabled" on certain websites. Now what do I do?

    I have tried every step you have listed in your FAQ section for enabling and disabling cookies but I am still getting error messages "cookies not enabled" on certain websites? Why is this and what do I need to do to fix this?

    I have STILL NOT received an answer to my question as of this date. I am VERY disappointed in Firefox support.

  • HttpURLConnection and URLConnection

    hi,
    what's the difference between HttpURLConnection and URLConnection ?
    When should I use the first and when the second one ?
    thanks

    The Javadoc shows the relationship. Cast a URLConnection to an HttpURLConnection when the URL protocol is HTTP.

  • How do I get and set cookies with JSF?

    How do I get and set cookies in a JSF managed bean?
    Regards,
    Al Malin

    Below is how I did it...I am receptive to improvements.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession)facesContext.getExternalContext().getSession(false);
    HttpServletRequest request = (HttpServletRequest)facesContext.getExternalContext().getRequest();
    HttpServletResponse response = (HttpServletResponse)facesContext.getExternalContext().getResponse();
    String cookieName = "myCookieName";
    Cookie requestCookie = null;
    Cookie[] cookies = request.getCookies();
    logger.info("looking for cookie...");
    if (cookies != null)
    for (int i = 0; i < cookies.length; i++)
    if (cookies.getName().equals(cookieName))
    requestCookie = cookies[i];
    logger.info(cookieName + " = " + requestCookie.getValue());
    logger.info("done looking for cookie");
    Cookie responseCookie = new Cookie(cookieName, "myCookieValue");
    responseCookie.setPath("/");
    response.addCookie(responseCookie);

  • Connot get it to accept cookies; privacy settings are re-set each time after I change them. How can I get the privacy setting to stick and accept cookies?

    I need to accept cookies to log into a technical site. I clear all cookies and the history and follow the instructions for setting privacy options to "Use custom settings for history" and to accept all cookies. When I go back to try logging into the site, it still tells me cookies aren't accepted. When I go back to Options-Privacy, the setting has been changed back to "Remember history" from "Use custom settings for history". I have done this about 5 times, trying various options, closing Firefox after making the change and starting it again - nothing works. How can I get the privacy settings to stay as I set them and accept cookies?

    Blocking all cookies in Safari does not work. Deleted cookies will not stay deleted. There are numerous threads on this going back years, both in these forums and elsewhere. Many claim to have submitted the issue to Apple, but I have never seen anyone post a reply.
    I have seen many suggested fixes that involve finding the cookies file, some including Terminal manipulations, and none seems to work universally. I can find noplace where Apple addresses this officially with an actual Apple-approved explanation or how-to.
    Bottom line, your browser's security features should do what they claim: delete cookies. When they come back without ever even visiting another page, this is clearly not working in the way a reasonable user would expect.
    Bottom line, Safari does not protect users' privacy in the way it pretends to and, after so many years of this issue, it appears that Apple wants it this way.
    Having spent way too much time on this, I realize the choice is between Safari which is pretty well optimized; Firefox which is a lot pokier, at least for me; and Chrome, which I assume funnels personal information directly to Google.

  • Safari allows 3rd party cookies and all cookies even when prefernces are set to "never allow" with Mac os 10.6.8

    safari ALWAYS allows 3rd party cookies and all cookies even when set to "block cookies: always" and "from 3rd party and advertisers."  I have removed the website data, emptied the cache, reset safari, erased the history and it STILL dumps cookies.  (For example, if I go to the usgov weather website only I end up with 11 cookies, the top one being "addthis.com" listed as cashed in local storage.  But didn't I just empty the cache... multiple times??? Is my Safari application "broken" or "corrupt."  Can the application be renewed so that it actually does what it is commanded to do?

    Not using any extensions, Andy.
    Allowed a guest account and tested that.  Lots of cache/cookies showed up for my "guest" that on face value, appeared 3rd party:  the familiar "addthis.com" cache and others including a facebook cache and I did not, nor have ever, participated in facebook. But it could be that the "trusted" site my virtual guest visited had a relationship with facebook such that my COMPUTER "friended" facebook even though my guest and I most certainly would have declined the invitation :-)  But what I really don't get is why washington post cookies keep showing up every single time.  Isn't that the absolute definition of 3rd party cookies?!
    forgive my rant.
    On the other hand, when I logged out as guest, all data was automatically deleted, and when I relogged in as guest, it appeared that all the data, including cached data, had indeed been deleted.  But when I relogged in as myself, the same old garbage reappeared in the cache and cookie bin. The fact is, there appears to be no such thing as truly and completely emptying ones cache, resetting ones browser, or deleting ones cookies. They are here to stay.
    (And, oh yes, I have tried logging out, turning off and on the computer right after performing emptying tasks, etc.)

Maybe you are looking for

  • Edit box length size problem...at Detail Section.

    hi. Plz have a look on below image. This is my problem. in details section i put one edit box... like below.. the data is comming from data base.. Header 1 but the size of the filed is more than the size of the Edit box.. i all ready checked  can gro

  • Problem with Virtual Credit Card Master Card

    (Sorry for my english, i am from Russia) I bought Virtual Credit Card Master Card and put its number and security code. Then I bought Pages, Keynote,GT Racing and some other apps. They have successfully downloaded and I can use them. But money from t

  • Inserting radio buttons in standard template of SRM EBP

    Hi All, We have modified the standard ITS service BBPSC01 template SAPLBBP_SC_UI_ITS  120 , to include two radio buttons as below: `if (gs_scr_itmovr_h-is_approver == "X")` <table> <tr> <td align="right" class="instruction"> <label for="apprrej"><inp

  • Rename files in PDF Generator

    Hi! This is the situation. I have an old aplication and im needed to print from it (over 80000 files). This app always print with the same name (ex RP001) so, i cant use a standard PDF printer, because it keep asking  to overwrite. I need to know if

  • Any way to do this with sed?

    I would like to be able to pipe the output from locate and have sed modify the files locate finds. Is there anyway to do this?