Cookies not getting in webrequest - c#

Below mentioned code is for getting cookie from the login url, I am trying to login and saving cookie to send it for further interaction, but I am not getting any cookie that can be passed. Please help
// My Login method::
void login()
{
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Constants.LOGIN_URL);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookieContainer;
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
string postData = "client_key=" + Constants.CLIENT_KEY + "&email=" + username + "&password=" + password;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
//webRequest.CookieContainer = cookieContainer;
//webRequest.Method = "GET";
HttpWebResponse response;
//Constants.userProfile.cookie = webRequest.CookieContainer;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
foreach (Cookie cookieValue in response.Cookies)
{
Console.WriteLine("Cookie: " + cookieValue.ToString());
}
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
// Overlay.Visibility = System.Windows.Visibility.Collapsed;
}
catch (WebException e)
{
Dispatcher.BeginInvoke(() =>
MessageBox.Show("Please try again", "Login Error", MessageBoxButton.OK));
Dispatcher.BeginInvoke(() =>
Console.WriteLine("Error Occurred" + e.Message));
}
}

Related

How can I retrieve campaign's placements from AdWords through api(.net)

How can I retrieve campaign's placements from AdWords through api(.net)?
I'd seen this piece of code, but I can't do something similar via c#.
Also I try to get links through report PLACEMENT_PERFORMANCE_REPORT, but I can't.
public static string GetReport(AdWordsUser user, string customerId)
{
string postData = string.Format("__rdxml={0}", System.Web.HttpUtility.UrlEncode(#"<reportDefinition xmlns=""https://adwords.google.com/api/adwords/cm/v201506"">
<selector>
<fields>CampaignId</fields>
<fields>Impressions</fields>
<fields>Clicks</fields>
<fields>Cost</fields>
<fields>FinalUrls</fields>
<predicates>
<field>Impressions</field>
<operator>GREATER_THAN</operator>
<values>0</values>
</predicates>
</selector>
<reportName>Custom Campaign Performance Report</reportName>
<reportType>PLACEMENT_PERFORMANCE_REPORT</reportType>
<dateRangeType>ALL_TIME</dateRangeType>
<downloadFormat>XML</downloadFormat>
</reportDefinition>"));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://adwords.google.com/api/adwords/reportdownload/v201506");
request.Headers.Add("Authorization", "Bearer " + user.OAuthProvider.AccessToken);
request.Headers.Add("developerToken", "MyToken");
request.Headers.Add("clientCustomerId", customerId);
request.Headers.Add("skipReportSummary", "true");
request.Headers.Add("skipReportHeader", "true");
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
var requestWriter = request.GetRequestStream();
requestWriter.Write(byteArray, 0, byteArray.Length);
requestWriter.Close();
string responseData = "";
try
{
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
responseReader.Close();
request.GetResponse().Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return "";
}
return responseData;
}

Saving login Cookie and use it for other request

I'm new to c#. I'm trying to login to a website, using a c# post request.
Does this code save the cookie actually to the CookieContainer and would it let me use this cookie in other requests also? How would I for example post a get request now with the cookie I saved from the login?
My main code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string userName = textBox1.Text;
string passWord = textBox2.Text;
string postData = "username=" + userName + "&password=" + passWord;
string requestUrl = "http://registration.zwinky.com/registration/loginAjax.jhtml";
post botLogin = new post();
botLogin.postToServer (postData ,requestUrl);
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
My post class:
public class post
{
public void postToServer(string postData, string requestUrl)
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
myHttpWebRequest.Method = "POST";
byte[] data = Encoding.ASCII.GetBytes(postData);
myHttpWebRequest.CookieContainer = new CookieContainer();
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.ContentLength = data.Length;
Stream requestStream = myHttpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream responseStream = myHttpWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
string pageContent = myStreamReader.ReadToEnd();
myStreamReader.Close();
responseStream.Close();
myHttpWebResponse.Close();
MessageBox.Show(pageContent);
}
}
You need to share the CookieContainer between the requests and the responses. I have similar code currently working:
public YourClass
{
private CookieContainer Cookies;
public YourClass()
{
this.Cookies= new CookieContainer();
}
public void SendAndReceive()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(...);
....
request.UserAgent = agent;
request.Method = "GET";
request.ContentType = "text/html";
request.CookieContainer = this.Cookies;
....
this.Cookies = (HttpWebResponse)request.GetResponse().Cookies;
}
}

How can be POST Audio file and get response WP8 C#

i'm trying to POST audio file to my Web Service and get Response from Server. I search on Google but no answer for Windows Phone 8. So please help me.
Update 1 Here my code to try Upload Audio file but have error on server
byte[] buffer;
void Upload(Stream fileStream)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://localhost:11111/api/SpeechRecognition?dataType=json"));
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.UseDefaultCredentials = true;
buffer = new byte[(int)fileStream.Length];
request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation.
Stream postStream = request.EndGetRequestStream(asynchronousResult);
postStream.Write(buffer, 0, buffer.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}
private void ResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = resp.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Dispatcher.BeginInvoke(new Action(() => { MessageBox.Show(responseString); }));
// Close the stream object.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse.
resp.Close();
}
In server ASP.NET 4.5 have error that line
await Request.Content.ReadAsMultipartAsync(provider);

How to make ordinary WebRequest async and awaitable?

I need to make the following code async and awaitable.
I need to get a lot of data from the web server, and then this data will be used to populate the xaml page in my application.
So, I need the DefLogin() method to be awaitable.
Is it possible?
public void DefLogin()
{
postData = "My Data To Post";
var url = new Uri("Url To Post to", UriKind.Absolute);
webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
Debug.WriteLine("Start BEGINGetResponse");
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
public void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
if (Response == "")
{
//show some error msg to the user
Debug.WriteLine("ERROR");
}
else
{
//Your response will be available in "Response"
Debug.WriteLine(Response);
}
}
catch (WebException)
{
//error
}
}
I saw this question on StackOverflow: Converting ordinary Http Post web request with Async and Await, but I could not understand the answer properly.
Please can anyone help? I would be really grateful!
You can use TaskFactory.FromAsync to convert APM to TAP, making a lot of tiny extension methods like this:
public static Task<Stream> GetRequestStreamAsync(this WebRequest request)
{
return TaskFactory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null);
}
and do the same for WebRequest.GetResponse and (if necessary) Stream.Write, Stream.Flush, etc.
Then you can write your actual logic using async and await without any callbacks:
public async Task DefLoginAsync()
{
postData = "My Data To Post";
var url = new Uri("Url To Post to", UriKind.Absolute);
webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
using (Stream postStream = await webRequest.GetRequestStreamAsync())
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
await postStream.WriteAsync(byteArray, 0, byteArray.Length);
await postStream.FlushAsync();
}
try
{
string Response;
using (var response = (HttpWebResponse)await webRequest.GetResponseAsync());
using (Stream streamResponse = response.GetResponseStream())
using (StreamReader streamReader = new StreamReader(streamResponse))
{
Response = await streamReader.ReadToEndAsync();
}
if (Response == "")
{
//show some error msg to the user
Debug.WriteLine("ERROR");
}
else
{
//Your response will be available in "Response"
Debug.WriteLine(Response);
}
}
catch (WebException)
{
//error
}
}

How to access Post data to access login data in windows phone

How to access the login authentication by the POST DATA in the below and it get from the httpFox to login the website. In other time i try to testing whether the GetRequestStreamCallback() operation will work and i found that the operation are not working and it end on the DoWork(). Why it not continue do the GetRequestStreamCallback() operation. Thanks For Helping me.
POST DATA
Parameter value
__EVENTTARGET
__EVENTARGUMENT
__VIEWSTATE /wEPDwUI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9XIEVUSEVSTkVUIDEyOE1CIGRkAgcPDxYCHwYFBVBNNDNBZGQCAg9kFgJmD2QWAmYPZBYIAgEPDxYCHwUFG34vcHJvZHVjdGltYWdlL0JBUjAxMTQ4LmpwZ2RkAgMPDxYCHwYFCEJBUjAxMTQ4ZGQCBQ8PFgIfBgVhWlNONVNLUjUxIFNLT1JQSU9YMyAxNFdPUktJTkcgREFZUyBUVVJOQVJPVU5EIEVBU0UgT0YgQ0FSRSBDT01QUkVIRU5TSVZFIENPVkVSQUdFIDUtWUVBUiBQQUNLQUdFRGRkAgcPDxYCHwYFCVNLT1JQSU9YM2RkAgQPZBYCZg9kFgJmD2QWCAIBDw8WAh8FBRt+L3Byb2R1Y3RpbWFnZS9TVkMwMDEyNC5qcGdkZAIDDw8WAh8GBQhTVkMwMDEyNGRkAgUPDxYCHwYFSVNFTlRJTkVMIDIwMTIgREFUQSBFWENIQU5HRSBJTlNUQUxMQVRJT04gVEVTSU5HIEFORCBUUkFJTklORyBPTlNJVEUgMSBEQVlkZAIHDw8WAh8GBQhTRU5USU5BTGRkGAIFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYCBRxMb2dpblZpZXcxJExvZ2luMSRSZW1lbWJlck1lBQ1BU1B4RGF0YVZpZXcxBQ1BU1B4RGF0YVZpZXcxDxQrAAdkZmYCA2YCFGdkMBSkuj/XQpQVVL41154MjHTriF3AqkB5ahYmcD10itw=
__EVENTVALIDATION /wEWBgLiiri0BQKRyKzhAgKUxtegDAKi77CUBwKd6MPGBALNx9K3CuAiLP9Qxn4q+Nwy4Hl2t5zaXX+GadHLKCF8sJn6YTar
LoginView1$Login1$UserName USERNAME
LoginView1$Login1$Password PASSWORD
LoginView1$Login1$LoginButton Log In
ASPxDataView1 0;3;3
DXScript 1_141,1_79,1_123,1_82
The below code is my work so far.
public void DoWork()
{
var url = "xxxxxxxx";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData =
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DoWork();
}

Categories