How to save cookies in HttpClient?

Hello. How can I save cookies with HttpClient?
With WebClients I used this:
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication1
public class WebClientEx : WebClient
public WebClientEx()
this.container = ReadCookiesFromDisk(cookiefile);
public CookieContainer CookieContainer
get { return container; }
set { container = value; }
private CookieContainer container = new CookieContainer();
private string cookiefile = "cookies.txt";
protected override WebRequest GetWebRequest(Uri address)
WebRequest r = base.GetWebRequest(address);
var request = r as HttpWebRequest;
if (request != null)
request.CookieContainer = container;
return r;
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
WebResponse response = base.GetWebResponse(request, result);
ReadCookies(response);
return response;
protected override WebResponse GetWebResponse(WebRequest request)
WebResponse response = base.GetWebResponse(request);
ReadCookies(response);
return response;
private void ReadCookies(WebResponse r)
var response = r as HttpWebResponse;
if (response != null)
CookieCollection cookies = response.Cookies;
container.Add(cookies);
WriteCookiesToDisk(cookiefile, container);
public void WriteCookiesToDisk(string file, CookieContainer cookieJar)
using (Stream stream = File.Create(file))
try
Debug.WriteLine("Writing cookies to disk...");
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, cookieJar);
Debug.WriteLine("Done.");
catch (Exception e)
Debug.WriteLine("Problem writing cookies to disk: " + e.GetType());
public CookieContainer ReadCookiesFromDisk(string file)
try
using (Stream stream = File.Open(file, FileMode.Open))
Debug.WriteLine("Reading cookies from disk...");
BinaryFormatter formatter = new BinaryFormatter();
Debug.WriteLine("Done.");
return (CookieContainer)formatter.Deserialize(stream);
catch (Exception e)
Debug.WriteLine("Problem reading cookies from disk: " + e.GetType());
return new CookieContainer();
So, just after that I have:
//This is first time we open page -> no cookies -> creating cookie 'test' with value '1'
var webclient = new WebclientEx();
var response = webClient.DownloadString("http://mydomain.com?act=viewcookies");
Debug.WriteLine(response);
//This is second time we open page -> if cookie 'test' exists, just reset value to '2' and if cookie 'test' does not exists, create 'test' with value '1'
var webclient2 = new WebClientEx();
var response2 = webclient2.DownloadString("http://mydomain.com/?act=viewcookies");
Debug.WriteLine(response2);
//Output
"We just created cookie 'test' with value '1'."
"We just reset cookie 'test' ('1') with new value '2'."
Well, simply, I need this code working with HttpClient instead of
WebClient (actually, you can tell me how to use WebClient in Windows Phone 8.1/Windows 8.1 Apps). Any thoughts?
Idea is to retrieve cookies from the page, just store them (I don't want even to open it), and then, at the second request, just pass this cookies to server.
I tried this:
CookieContainer cookies = new CookieContainer();
for(int i = 0; i < 2; i++)
HttpClientHandler handler = new HttpClientHandler
AllowAutoRedirect = true,
UseCookies = true,
CookieContainer = cookies
var client = new System.Net.Http.HttpClient(handler);
var response = await client.GetStringAsync(new Uri("http://mysite.com/?act=viewcookies"));
System.Diagnostics.Debug.WriteLine(response);
... and I got this:
//Output with HttpClient
"We just created cookie 'test' with value '1'."
"We just created cookie 'test' with value '1'."
It looks like HttpClient doesn't store cookies in CookieContainer.

try with :
MessageProperties props = OperationContext.Current.IncomingMessageProperties;
HttpResponseMessageProperty prop = props[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
sharedCookie = prop.Headers["Set-Cookie"];

Similar Messages

  • How to save cookies in files

    I use add cookies in servlet and then use httpClient.getState().getCookies() to retrieve this cookie.
    Now I would like to save it in "C:\Documents and Settings\lior\Cookies" folder but since domain name is not the local domain name it is not saved.
    How can I do that?
    Thanks,
    Lior.

    What can couse HttpServletResponse addcookie not to save cookie on hard disk??
    The max age is set to:
    int maxAge = 3600 * 24 * 365;
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);
    The cookie created and returnd to the HttpClient BUT not writen to the disk??
    Lior.

  • How to save object to SQLite?

    Hi,
    I am confusing with this.
    How to save object (instance of class) to SQLite and read the
    object back to Flex?
    Thanks
    Mark

    SQLite is a relational database, not an object-oriented
    database, so you can't just spit an object into it without
    translation. You
    could serialize it with JSON or XML and store that in a
    column, but then you're giving up most of the benefit of a proper
    database engine. It's best to flatten the object yourself into the
    database structure. How you do that, exactly, depends on your
    object structure(s).
    So, if you have an object like this:
    var foo:Object = { bar: 'qux', bletch: new Date(), farbly: [
    42, 69 ] };
    you probably need two tables to represent it: a main "foos"
    table (a collection of foo objects) and a separate "farblys" table
    to hold the array elements. This separation of arrays out into a
    table of their own linked to the original table is called
    normalization.
    Normalization will be covered in any decent tutorial book on
    SQL databases. You'll need to get one to best understand how to
    utilize SQLite, or anything like it. I got a lot out of
    The
    Practical SQL Handbook. I doubt that it covers SQLite
    specifically. I have an older edition, so I can't check, but the
    current edition was released about the same time that SQLite was,
    and SQLite took some time to get noticed. The
    SQLite Documentation
    will fill in the gaps. The main thing to beware of is that SQLite
    doesn't support all the advanced things you will read about in a
    general SQL book.
    If you don't want to mess with all this object-relational
    mapping and normalization stuff, and you don't have much data to
    store, you might look into Flash Local Stored Objects (LSO), also
    called "Flash cookies". The runtime has a default limit of 100 KB
    of data per application. The advantage of LSOs is that you can use
    them like any other ActionScript object, and Flash handles the
    storage details for you. It's great for configuration data and
    small bits of user data.

  • How to store cookies fade gradually according to date?

    i want to save cookies in folder date everyday, how to do that?

    I solved that filling last descrition of each "CONTROL" in transfer rule

  • ALV Grid: how to save changes made in an editable Grid

    Hi,
    How to save changes made bu the user in any of the editable cells in a ALV Grid?
    Regards,
    deb.

    Hi,
    If you are using the FM look at the following example code...
    data: LC_GLAY TYPE LVC_S_GLAY.
    LC_GLAY-EDT_CLL_CB = 'X'.<<<<<------
    gt_layout-zebra = 'X'.
    gt_layout-detail_popup = 'X'.
    gt_layout-colwidth_optimize = 'X'.
    call function 'REUSE_ALV_GRID_DISPLAY'
    EXPORTING
    i_callback_program = i_repid
    i_callback_user_command = 'USER_COMMAND1'
    it_fieldcat = header
    is_layout = gt_layout
    i_callback_top_of_page = 'TOP-OF-PAGE1'
    i_grid_title = text-h17
    it_sort = gt_sort[]
    i_default = 'X'
    i_save = 'U'
    is_variant = gt_variant
    it_events = gt_events
    I_GRID_SETTINGS = LC_GLAY<<<<<<------
    TABLES
    t_outtab = itab.
    clear itab.
    Form USER_COMMAND1
    FORM USER_COMMAND1 USING u_ucomm LIKE sy-ucomm
    us_selfield TYPE slis_selfield."#EC CALLED
    case u_ucomm.
    when '&DATA_SAVE'.<<<<<<<<----
    This will come after the data was EDITTED and when SAVE was clicked by user in output scren.
    Here now in the final internal table(ITAB) you can find the data changed in EDIT mode.
    After this you can do manipulation what ever you want.
    Thanks.
    If this helps you reward with points.

  • How to save my voice memos in windows laptop as I already know how to synchronise ?

    How to save my voice memos from iPhone to windows laptop after syncronising with iTunes which memos are 1hr longer?

    Usually it goes to the last folder used or the folder the current PDF was opened from (I am getting the latter in my current Acrobat). If you want a different folder, you will have to go through the tree to your desired folder process.

  • I can't figure out how to save my events onto an external hardrive

    I have been looking at the event libraries and everywhere to figure out how to save my files onto an external hardrive. I currently use FCPX to edit Call of Duty Montages for people as my job so I need this to work. I don't know what I'm doing wrong and I really need storage.

    In the Copy Files Into: field there is a pop up that allows you select where your media is copied to.
    Looking at the above screen shot if I want files to be copied to my External LaCie drive I just tick that one.
    Firstly you will have to create at least one Library on the External to send it there.
    There is the CHOOSE option that allows you to navigate anywhere on the the system to manually select a destination.
    Al

  • How to save report in PersonalCategory  after creating it using java panel?

    Hi,
    Anybody knows How to save report in PersonalCategory  after creating it using java panel?
    I dont want to save it in public folder. I want to save report (webi) in user's personal category.
    can anybody send me source code?
    It will help me a lot.
    Thanks in advance
    Amol Mali

    Hi teda,
    i'm assuming that you have seen my post that i did successfuly save report in user's personal category.
    Actually the report is created in webi java panel using RE SDK and  is saved in Report Sample Folder then i'm saving it in user's personal category by following code
    string query = "Select SI_PERSONAL_CATEGORIES From CI_INFOOBJECTS Where "
                         + "SI_INSTANCE=0 And SI_ID=" + reportID;
                    InfoObjects infoObjects = infoStore.Query(query);
                    InfoObject infoObject = infoObjects[1];
                    Webi wreport = (Webi)infoObject;
                    ObjectRelativeIDs personalIDs = wreport.PersonalCategories;
                /personalIDs.Add(Convert.ToInt32(categoryID));
                   infoStore.Commit(infoObjects);
    But the report is presents in the Folder also and in user's personal category also.
    I dont want the report to be in the folder (Report Sample) if i saved it in user's personal category.
    How can i do that?
    any idea.
    Please help me.
    Thanks in advance
    Amol Mali
    Edited by: amol mali on Jan 9, 2009 7:55 PM

  • How to save JList items!

    hello,
    i m creating a class that has three JList components.
    My problem is how to save the each JList items into a seperate logfile(ie. text file).

    More info required:
    What are in the JList? Strings? Custom objects?
    Do you know basic file IO?
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    What you will need to do is get the model, ilterate over each element, then write that element out. If the element is a string, then that is easy, just create a FileWriter, and write the string, followed by a new line.
    If it is a custom object, then the task is harder, and you need to decide how that object should be represented.
    If you are after a computer readable view of the model, rather than a human readable, which can easily be read by Java back into a ListModel, then you want to look at XMLEncoder and XMLDecode, or the Serializing Objects tutorial.
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

  • How to save data in ztable after editing in alv report

    how to save data in ztable after editing in alv report?

    Hi,
        Please find the attachment below.This may be usefull to you.
         [http://wiki.sdn.sap.com/wiki/display/Snippets/ALV-Editingandsavingtheeditedvaluesin+Database%28OOPS%29]
    Regards,
    Ramakrishna Yella.

  • I need to erase the contents of my phone and restore to factory settings. Does anybody know how to save your texts so you don't lose them?  Can I back those up to iCloud?  My phone was very likely hacked (Apple's advice was to call the police!)

    "I need to erase the contents of my phone and restore to factory settings. Does anybody know how to save your texts so you don't lose them?  Can I back those up to iCloud?  My phone was very likely hacked (Apple's advice was to call the police!)"
    That was all I could put in the initial "box."  Then it brought me to this page with instructions on how to write a good sentence.
    Proceeding ...
    After going back and forth between Apple, AT&T and the police (all telling me to go to the other two) I took AT&Ts suggestion and got a new number. One tech warned against doing a backup, especially on my Mac, saying if my phone had been hacked then whatever bug was there would then invade my computer. But nobody knows how to determine if the phone has been hacked or a virus was planted there. Unfortunately I know who would have reason to do such a thing and all I can say is that he is at the top technologically and could easily do it. Almost impossible to prove, however.
    So I need to preserve my text messages and my emails as well. I backed up my photos to that Microsoft product (One-Drive) and it froze (Surprise, Surprise) with four short videos to go, and no way of stopping that (when I tried it crashed repeatedly) so I'm in crisis mode here.
    Help ...
    Running 8.0 on 5S
    Thanks!

    Betty I don't know if you fixed your hacking problem but I feel your pain. I've seen some strange things going on between my iMac and my iPhone and Apple has told me the same thing, call the police which I have done. The hackers have stole 500.00 out of my checking account have access to every internet account I use and no matter how often I change the password their right back on the account. I closed my FB account 3 times only to have someone reopen it. Right now I've got a link in my reading list (Safari) that if I click on it, it allows me to log onto my FB account anonymously.
    I've seen a green folder come out of no where while I was trying to delete my passwords out of keychain when that green folder was put into the key chain I was immediately locked out. I than went into system preferences to try to make changes to my security settings, when I clicked on the icon it wouldn't open. I've seen log files of automator receiving commands and sending out my personal information thats on my computer.
    I have a legitamate program called iExplorer that allows you to look at the contents of your iPhone back ups and saw a transaction someone made at the Apple store for some full length movies, some albums, ibooks and other apps but when I called the iTunes store and they said none of those items were showing up on my account. If their not on my account how can they be on my iPhone 6? One day someone was using my gmail account and unknowingly used google maps to search for an Italian restaurant, than a Mexican restaurant than a coffee shop and their search showed up on my iPhone but I didn't have my gmail account installed on my iPhone 6. Using my computer I logged onto my gmail account and looked at the maps history and sure enough there were the searches when I'd hover my curser over the link it gave me the longitude and latitude of the where the hacker was when he was using google maps. I know whoever reads this thinks Im crazy but I've documented everything and can prove the things that I have mentioned in this post actually happened.
    One day I had my laptop (pc) and my iMac next to each other as I was using both. when I clicked on airport it showed that my laptop and my iMac had made a connection and were actually communicating with each other. I know I didn't do it I don't know how. The iMac was logged into my iCloud account while my laptop wasn't. I have formatted my iPhone at least a dozen times, Apple and an Apple retailer have formatted my hard drive not to mention the numerous times I have formatted it but the hackers keep getting on my devices. Im formatting my lap top at this very second because during the course of the night I left the ethernet cable plugged into it and they locked me out of my c: drive, and configured the system so I can't download any updates from Microsoft, overtime I type in www.microsoft.com it changes to ww38.microsoft.com which takes me to a blank page. I right clicked on the page I was redirected to and read the java script and couldn't believe that someone had actually configured Internet Explorer to redirect me to a blank page when I tried to go to Microsoft. Apples answer to all this is there was nothing wrong with my iPhone or my iMac and if I thought there was a problem to call the police which I have done.
    Theres no doubt the hackers are reading this while I type it or will read it and I simply don't care anymore. I no longer email anyone, don't use my iCloud account and have taken precautions to protect my credit but if I ever find out who has invaded my privacy to this extreme the police are going to want to talk to me because Im going to hurt them like they've never been hurt before

  • How to save picture from an iPad on someone else computer

    how to save picture from an iPad on someone else computer.

    Why don't you save pictures to Dropbox?
    You don't have to save it on someone's computer
    http://i1224.photobucket.com/albums/ee374/Diavonex/b90c9d4d.jpg

  • How to save a datas from serial port?

    How to save a datas from serial port?

    Hi
    I need some help about rs-232 communication. I want to make a vi witch can do this things:
    -read a txt file (to simulate a serial port like when the datas are coming)
    i will get 3 different data in serial port (like this: 121 213 135)
    i want to save in a txt file what datas get my vi
    so
    -write in a txt file or draw in a diagram (or both)
    so my problem is: read in serial port and save in a file and draw a diagram.
    if anybody can help pls HELP ME because im a beginner in this problem.
    I already do something but Im not sure that good.
    Thx for all.

  • Please can someone tell me how to save a MP3 file from my email on my iPad so I can put in on Facebook? Thankyou

    Please can someone tell me how to save a MP3 file from my email on my iPad so I can put it on Faceboo? I use hotmail and please tell me step by step as I am not a tech guru lol. Thankyou

    Hi jscher200,
    Thank you for your reply, sorry for the VERY late late response, but I have just figured out how to control this separate 'panel'. I find it really useful for monitoring Google Analytics in as it can just sit there running. It does have its limitations, as it's a limited size (you can't expand it to full screen view), so you can only ever see a vertical section of a website and need to scroll to look to the right or left, but I have the live view of people accessing my website running on there and if the numbers start racking up at any time, I can scroll to look and see what pages they are accessing, where they've been referred from, etc.
    To get it to work, you save a website address in the Bookmarks Toolbar and when you can see it sitting on the toolbar at the top of the screen with its little icon, right click on it then click 'properties', then tick the box 'Load this bookmark in the sidebar'. The next time you click on this bookmark to open the website, it will load in this sidebar, which looks like a separate 'window' but is immovable. You can only have one sidebar application running at a time, but can change it by right clicking on the bookmark you want to load in there and it will then change to that one next time you click on that bookmark.
    I hope this might be useful to others, as I asked for help with this on loads of forums and not one person knew that this existed - even really skilled techies!

  • New to Photoshop;Viewing TV and want to save to MY Library to view later. Can't figure out how to save. When I open or click on My Library it shows I need to sign in and within a few seconds it shows my sign in but nothing changes on page.

    Trying to figure out how to save Adobe TV episode as I am new to Photoshop and need insruction... trying to open & save to My Library to view later. It instructs me to sign in but I am already signed in. Anyone know how?

    Those are the instructions for your computer's iTunes (i.e. using the Store menu at the top of your computer's iTunes and selecting 'View My Account' on it). If you are doing it on your iPad then are you following the instructions for iOS devices :
    To unhide your purchases
    Depending on the content type, open the App Store, iBooks, or iTunes Store on your device.
    Scroll to the bottom of the main page.
    If you're not already signed in, tap Sign In.
    Tap your Apple ID name, then tap View Account.
    Scroll down on the Account pane, and tap Hidden Purchases.
    Locate the item you would like to unhide then tap the Unhide button.

Maybe you are looking for