httpwebrequest cookies from response - c#

How can I use the cookies from a response in a new request?
So basically I have an if statement within my getresponse stream for redirects,
Example of code -
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream2 = response.GetResponseStream())
{
if ((int)response.StatusCode >= 300 && (int)response.StatusCode <= 399)
{
string newurl = "https://www.example.com/page2";
request = request = (HttpWebRequest)WebRequest.Create(newurl);
}
using (StreamReader reader = new StreamReader(stream2, Encoding.UTF8))
{
str6 = reader.ReadToEnd();
}
}
return str6;
}
How can I apply the response cookies/header data to my new request -
request = request = (HttpWebRequest)WebRequest.Create(newurl);
I know if I do
response.Headers["Location"];
it'll give me the response location, but what about cookies? & how could i apply those cookies to the request

var myCookie = new HttpCookie("token");
myCookie.Value = Guid.NewGuid().ToString();
myCookie.Expires = DateTime.UtcNow.AddHours(10);
response.Cookies.Add(myCookie);

Related

How do I access the results of a JSON object in C#

How can I loop through the JSON results from this C# Rest API call:
string url = string.Format("https://example.com/api/mytext");
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "mykey";
req.Accept = "text/json";
using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
{
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
// how do I access the JSON here and loop through it?
}
}
There is no "data" in the resp object:
Visual Studio doesn't seem to show any results in "resp" - but I know they are there, as I've seen results in postman.
Thanks, Mark
Use GetResponseStream() with a StreamReader
string url = string.Format("https://example.com/api/mytext");
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "mykey";
req.Accept = "text/json";
using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
{
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
string contents;
// how do I access the JSON here and loop through it?
using(var responseStream = resp.GetResponseStream())
using(var responseStreamReader = new StreamReader(responseStream))
{
contents = responseStreamReader.ReadToEnd();
}
var deserializedContent = JsonConvert.DeserializeObject<T>(contents);
}
}
See more on GetResponseStream
See more on StreamReader
See more on JsonConvert
Dependencies: Newtonsoft.Json
Use HttpWebResponse.GetResponseStream method to get the result as a Stream. Then you can use Newtonsoft JSON.NET to parse the result.
using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
{
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
using (var stream = resp.GetResponseStream())
{
// Process data with JSON.NET library here
}
}
}
dynamic dynJson = JsonConvert.DeserializeObject(response);

Yahoo api for fantasy sports. Cannot figure how to use access token

I have the access token. How can I make a request using the token in c#?
Here is what I have tried unsuccessfully resulting in error 400 Bad Request.
Note: the url was copied from the YQL console
public static void Request(string token)
{
var request =
WebRequest.Create(
#"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20fantasysports.leagues%20where%20league_key%3D'371.l.4019'&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
request.Headers["Authorization"] = $"Bearer {token}";
request.Method = "GET";
request.ContentType = "application/xml;charset=UTF-8";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream == null) return;
var reader = new StreamReader(stream, Encoding.UTF8);
var responseString = reader.ReadToEnd();
}
}
}

How to get OTCSticket with api/v1/auth method=post in content server using c#

Following is the API Call i make using postman and get a ticket back in the response body (screenshot):
I am not able to get the ticket in a HttpWebRequest Response in C#. Please below see the small sample code:
C# code
HttpWebRequest Request = WebRequest.Create(strUrl) as HttpWebRequest;
Request.Method = "POST";
Request.Headers.Add("Authorization", "Basic <>");
//Request.ContentType = "application/form-data";
Request.KeepAlive = true;
string data = string.Format("username=" + UserName + "&password=" + Password);
byte[] dataStream = Encoding.UTF8.GetBytes(data);
Request.ContentLength = dataStream.Length;
using (Stream newStream = Request.GetRequestStream())
{
// Send the data.
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
}
var Response = (HttpWebResponse)Request.GetResponse();
using (var stream = Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
if (Response.StatusCode != HttpStatusCode.OK)
throw new Exception("The request did not complete successfully and returned status code " + Response.StatusCode);
ResponseTicket strTicket= JsonConvert.DeserializeObject<ResponseTicket>(reader.ToString());
JsonConvert.DeserializeObject(Response.GetResponseStream().ToString());
MessageBox.Show(strTicket.Ticket);
}
Where as statuscode=200. But the content length is 0.
It is very difficult to find any meaning full help on CS10.5 API. I have checked there AppWorks platform but in vain. Would appreciate if someone can find the problem in the code, which apparently i can not see.
I don't know if this is still an issue for you. For me it was also, but figured it out:
public string LoginAsAdminAndRetrieveTicket(string userName, string passWord, string domain, string url)
{
var uri = $"http://{url}/otcs/llisapi.dll/api/v1/auth";
var request = new HttpRequestMessage();
request.Headers.Add("Connection", new[] { "Keep-Alive" });
request.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
request.Headers.Add("Pragma", "no-cache");
request.RequestUri = new Uri(uri);
request.Method = HttpMethod.Post;
request.Content = new StringContent($"username={userName};password={passWord}", Encoding.UTF8, "application/x-www-form-urlencoded");
var httpClientHandler = new HttpClientHandler
{
Proxy = WebRequest.GetSystemWebProxy(),
UseProxy = true,
AllowAutoRedirect = true
};
using (var client = new HttpClient(httpClientHandler))
{
var response = client.SendAsync(request).Result;
string ticket;
var vals = response.Headers.TryGetValues("OTCSTicket", out IEnumerable<string> temp) ? temp : new List<string>();
if (vals.Any())
{
ticket = vals.First();
}
return response.Content.ReadAsStringAsync().Result;
}
}

WP8 - Login to Website and parse HTML from answer

I want to login to this site: http://subcard.subway.co.uk/de_cardholder/JSP/login_reg.jsp
And i found out that I have to send a POST request to the server and I also know that I have to work with this POST request:
POST /de_cardholder/servlet/SPLoginServlet HTTP/1.1
Host: subcard.subway.co.uk
language=de&userID=ID&password=PASSWORD&transIdentType=1&programID=6
And after the login I want to parse the HTML data. But how can I implement the POST request on WP in C# and is it as easy as I think?
Try this,
Uri RequestUri = new Uri("subcard.subway.co.uk/de_cardholder/servlet/SPLoginServlet HTTP/1.1?language=de&userID=ID&password=PASSWORD&transIdentType=1&programID=6", UriKind.Absolute);
string PostData = "";
WebRequest webRequest;
webRequest = WebRequest.Create(RequestUri);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
HttpWebResponse response;
string Response;
using (response = (HttpWebResponse)await webRequest.GetResponseAsync()) ;
using (Stream streamResponse = response.GetResponseStream())
using (StreamReader streamReader = new StreamReader(streamResponse))
{
Response = await streamReader.ReadToEndAsync();
}
if(Response != null)
{
//data should be available in Response
}
var postRequest = (HttpWebRequest)WebRequest.Create("your Url here");
postRequest.ContentType = "application/x-www-form-urlencoded";// you can give the type of request content here
postRequest.Method = "POST";
if you have any data to be posted along with the request as part of content and not as part of URL itself you can add this. example:- ( language=de&userID=ID&password=PASSWORD&transIdentType=1&programID=6)
using (var requestStream = await postRequest.GetRequestStreamAsync())
{
byte[] postDataArray = Encoding.UTF8.GetBytes("your request data");
await requestStream.WriteAsync(postDataArray, 0, postDataArray.Length);
}
if you do not have any data to be a send as content ignore the above code
WebResponse postResponse = await postRequest.GetResponseAsync();
if (postResponse != null)
{
var postResponseStream = postResponse.GetResponseStream();
var postStreamReader = new StreamReader(postResponseStream);
string response = await postStreamReader.ReadToEndAsync();// Result comes here
}

IHttpHandler send cookie back to calling website

I have an ordering website that needs to make a set up request on a supplier site.
For this i am using a WebHanlder (ashx file) to read the setup request in cXML using the HttpContext object which is working fine.
One of the requirements is that we send back a Cookie called "Buyer Cookie" along with a cXML 200 OK response.
The problem I am having is when I create a cookie in the context.Response it is not recieved in the ordering site when I do the response.Output.Write().
I have tried using response.Flush() after the write and this is still not working
How can I send a cookie back to the calling site?
Here is my code:
Ordering site
Stream stream = null;
byte[] bytes = Encoding.ASCII.GetBytes(File.ReadAllText(#"D:\Prototypes\HTTPPost\cXMLFiles\PunchOutSetupRequest.xml"));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:45454/PunchOutRequest.ashx");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.ContentLength = bytes.Length;
try
{
stream = webRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
}
catch (Exception)
{
throw;
}
finally
{
if (stream != null)
stream.Close();
}
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string r = responseReader.ReadToEnd();
var buy = webRequest.CookieContainer;
var buyer = response.Cookies["BuyerCookie"]; // This is always null
Supplier Site
var request = context.Request;
StreamReader reader = new StreamReader(request.InputStream);
string text = reader.ReadToEnd();
POSetup setup = new POSetup();
if (setup.IsSetupRequestValid(text))
{
HttpCookie cookie = new HttpCookie("BuyerCookie", "100");
context.Response.Cookies.Add(cookie);
context.Response.Output.Write(setup.GetOKResponse());
}
Try adding this line:
webRequest.CookieContainer = new CookieContainer();
right after
webRequest.ContentLength = bytes.Length;

Categories

Resources