Maintaining session with web server - c#

I have a WCF service that is consuming a website. Before anyone points out the obvious flaw and inherent instability in this approach, please forgive me, i have been forced to work on this.
The flow of the transaction is as follows :
Channel -> WCF Service ->(HTTP POST/GET) -> Website
Steps :
PostStrOnUrlRandom is called in a loop, passing it the string to be posted(strPost), the url(url) and CookieJar(CookieJarR) containig cookies from previous post.
HTTP GET on the url(not in below code)
I get the HTML page in response, parse it using XPATH, confirm it is correct page and save Cookies
POST strPost passed on this method on the url.
Get response HTML page, parse it using XPATH
Fetch next url and strPost from DB
Post the next strPost on the next url
I have to do this for 5 urls. Then i have to send response back to the Channel. The Channel then sends me another request, and i have to do another POST. I do this by using the same cookies I used for previous requests.
This is where the problem arises, I get back an Internal Server Error 500. If i do retires on this POST, using the same strPost, url and Cookies it works after 3-4 retires. I cannot understand why this is.
Code is as follows :
public HttpWebPostResponse PostStrOnUrlRandom(string url, string strPost, string Refer, CookieCollection cookieJarR)
{
log.Debug("Method Entery [PostStrOnUrl]");
StreamWriter myWriter = null;
string resultHtml = null;
HttpWebResponse objResponse = null;
HttpWebPostResponse hpr = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.ProtocolVersion = HttpVersion.Version10;
objRequest.Timeout = 90000;
objRequest.CookieContainer = cookieJar;
objRequest.Method = "POST";
objRequest.ContentType = "application/x-www-form-urlencoded";
objRequest.AllowAutoRedirect = true;
objRequest.MaximumAutomaticRedirections = 100;
objRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0";
objRequest.Referer = Refer;
objRequest.Host = ConfigurationManager.AppSettings["Host"];
objRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
objRequest.Headers.Add("Origin", ConfigurationManager.AppSettings["Origin"]);
objRequest.Headers.Add("Cache-Control", "max-age=0");
objRequest.Headers.Add("Accept-Encoding", "gzip, deflate, br");
objRequest.Headers.Add("Accept-Language", "en-US,en;q=0.8");
objRequest.KeepAlive = true;
log.Debug("Making HttpWebRequest to" + url);
Uri target = new Uri(url);
log.Debug("Target Url : " + url.ToString());
foreach (Cookie cookie in cookieJarR)
{
objRequest.CookieContainer.Add(cookie);
cookieJar.Add(cookie);
log.Debug(cookie.Name + "" + cookie.Value + "" + "" + cookie.Domain);
}
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
log.Debug("Posting on Url StrPost =" + strPost);
}
catch (Exception e)
{
log.Debug(e.Message);
}
finally
{
myWriter.Close();
}
log.Debug("Making Request.");
try
{
objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
resultHtml = sr.ReadToEnd();
sr.Close();
}
hpr = new HttpWebPostResponse(objResponse.ResponseUri.ToString(), resultHtml, objResponse.StatusCode.ToString());
return hpr;
}
catch (Exception e)
{
log.Error(e.Message);
log.Error("Exception", e.InnerException);
return null;
}
}

Related

POST or Get Request with Json response in C# windows Form App

I made an API in server side with PHP + Laravel framework which accept both GET & Post requests with some special parameters.
It's address is : http://beresun.ir/API/Orders/0
and it gets these parameters :
token > string ,
restaurant_id > integer ,
admin_id > integer ,
token_id > integer .
if we send a request with GET method with these parameters, for example it will be :
http://beresun.ir/API/Orders/0?token=2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP&restaurant_id=1&admin_id=2&token_id=40 which returns a json data , you can click on the link to see the results .
the response json data includes some information about customers and it's products.
now I want to make a windows application for this service with C# and request data from this API with POST or GET methods :
I want to use this API to get Json data from Web server and save them in my Windows application , So I created two functions in one of my Form Classes :
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
public partial class MainActivity : Form
{
string token = "2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP";
int restaurant_id = 1;
int admin_id = 2;
int token_id = 40;
private void SendWebrequest_Get_Method()
{
try
{
String postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://beresun.ir/API/Orders/0?" + postData);
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.Method = WebRequestMethods.Http.Get;
WebResponse response = request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
String json_text = sr.ReadToEnd();
dynamic stuff = JsonConvert.DeserializeObject(json_text);
if (stuff.error != null)
{
MessageBox.Show("problem with getting data", "Error");
}
else
{
MessageBox.Show(json_text, "success");
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Wrong request ! " + ex.Message, "Error");
}
}
private void SendWebrequest_POST_Method()
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://beresun.ir/API/Orders/5");
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
// Create POST data and convert it to a byte array.
string postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json; charset=utf-8";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
MessageBox.Show(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show("Wrong request ! " + ex.Message, "Error");
}
}
}
Now Here is the problem , when I test the API it works fine , but when I request data from my application , it returns error and not working .
Can anyone explain me how I should request data from this API , to get data , I searched a lot , and I used many different methods , but none of them worked for me . maybe because this API returns very much Json data or maybe request timeout happen. I don't know , I couldn't find the problem . So I asked it Here.
I don't know what I should do .
Thanks
Oki so i run your code :
private string TestURL = "http://beresun.ir/API/";
string token = "2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP";
int restaurant_id = 1;
int admin_id = 2;
int token_id = 40;
public async Task<string> test()
{
try
{
using (var Client = new HttpClient())
{
Client.BaseAddress = new Uri(TestURL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
HttpResponseMessage responce = await Client.GetAsync("Orders/0?" + postData);
if (responce.IsSuccessStatusCode)
{
var Json = await responce.Content.ReadAsStringAsync();
// !
return Json;
}
else
{
// deal with error or here ...
return null;
}
}
}
catch (Exception e)
{
return null;
}
}
and its working am getting the json file ,, i think your mistake is in postData is string Not String ! a simple type can amazing harm !
try this:
private string URL = "Your Base domain URL";
public async Task<YourModel> getRequest()
{
using (var Client = new HttpClient())
{
Client.BaseAddress = new Uri(URL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage responce = await Client.GetAsync("Your Method or the API you callig");
if (responce.IsSuccessStatusCode)
{
var Json = await responce.Content.ReadAsStringAsync();
var Items= JsonConvert.DeserializeObject<YourModel>(Json);
// now use you have the date on Items !
return Items;
}
else
{
// deal with error or here ...
return null;
}
}
}

How can i reuse cookies from HttpWebResponse to stay logged in on a web page?

I have a case with a simple application that browses to a XenForo Forum site, fetches cookies and further sends post data to login and fetch some information only available for logged in users.
I am able to successfully fetch the cookies and verify that i am successfully logged in the first time, but i cant seem to stay logged in when i try to "browse" further when trying to reuse the same cookies.
Here is what i got so far:
public MainWindow()
{
InitializeComponent();
if (IsLoggedIn())
{
GetPage("http://thesiteiloginto.org/someotherpage");
}
}
// Store Cookies
CookieCollection Cookies;
void GetCookies(string cookieUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(cookieUrl);
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
// Store Cookies
Cookies = response.Cookies;
}
}
bool IsLoggedIn()
{
GetCookies(_cookieUrl);
CookieCollection cookies = Cookies;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postData = "login=" + username +
"&password=" + password +
"&_xfToken=" + xfToken +
"&cookie_check=" + cookie_check +
"&redirect=" + redirect;
byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
if (cookies != null)
{
Console.WriteLine("Cookies are present");
Console.WriteLine(Cookies.Count);
Console.WriteLine(Cookies[0].Value);
request.CookieContainer.Add(cookies);
}
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
WebResponse response = request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(reader.ReadToEnd());
bool _loggedIn = false;
try
{
var uniqueNodeTest = doc.DocumentNode.SelectSingleNode("//*[#id=\"navigation\"]/div/nav/div/ul[2]/li[1]/a/strong[1]");
if (uniqueNodeTest.InnerText.Trim().ToLower() == uniqueNodeName)
{
Console.WriteLine("Logged in");
_loggedIn = true;
}
}
catch (Exception ex)
{
Console.WriteLine("Ops! [Login] # SelectSingleNode\n" + ex.Message);
_loggedIn = false;
}
return _loggedIn;
}
}
}
}
void GetPage(string url)
{
if (Cookies != null)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(Cookies);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
var pageSource = reader.ReadToEnd();
// Retuns false, meaning i am not logged in
//Where do i go from here?
Console.WriteLine(pageSource.Contains("Log Out"));
}
}
}
}
Console:
Cookies are present
1
22a6c5a4c5557a7f7db36f50a1d746f1
Logged in
False
As you can see i am logged in after the first test, but i cant seem to stay logged in when trying to further browse reusing the cookies.
What am i not taking into consideration? How can i stay logged in to the site?
Use CookieContainer as class to store them locally.
When retrieving the response, put all your cookies into the CookieContainer. When preparing the request, just set the request.CookieContainer to your own object on the new call.
This is the code I used for saving my cookies in a project of mine. Since it's part of one fully decked out HttpSession class specifically meant for the kind of requests you're doing, you'll notice both the response and the cookie container are class variables.
/// <summary>
/// Fetches the new cookies and saves them in the cookie jar.
/// </summary>
private void SaveNewCookies()
{
try
{
foreach (Cookie c in this.m_HttpWebResponse.Cookies)
{
if (c.Domain.Length > 0 && c.Domain[0] == '.')
c.Domain = c.Domain.Remove(0, 1);
this.m_CookieJar.Add(new Uri(this.m_HttpWebResponse.ResponseUri.Scheme + "://" + c.Domain), c);
}
if (this.m_HttpWebResponse.Cookies.Count > 0)
this.BugFixCookieDomain(this.m_CookieJar);
}
catch
{
// no new cookies
}
}
As you see, this contains some smaller bug fixes as well. The mentioned BugFixCookieDomain function is a fix specifically for the 3.5 framework, which you can find here, but if you've moved past that to 4.0 and beyond it won't be particularly useful to you.

Integration of Rightmove Real Time Data Feed (RTDF) asp.net

i am integrating rightmove real time data feed (rtdf) in my property site for listing my properties on rightmove website. i am using asp.net web api to post data on rightmove listing.
they have provide me with these SSL Files [.p12,.pem,.jks]. i have imported .p12 certificate in my local machine personal store and sending it in my http request
to rightmove test api link provide by rightmove.
i am getting the following error from server.
The remote server returned an error: 403 forbidden.
i checked my certificate loaded successfully in the request, below is my code
public static string PostData(string data, string url)
{
String result = "";
try
{
byte[] bytebuffer = Encoding.UTF8.GetBytes(data);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = bytebuffer.Length;
objRequest.ContentType = "application/json";
objRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0";
objRequest.PreAuthenticate = true;
objRequest.Accept = "application/json";
objRequest.ClientCertificates.Add(CertificateHelper.GetRightmoveApiX509Certificate());
using (Stream stream = objRequest.GetRequestStream())
{
stream.Write(bytebuffer, 0, bytebuffer.Length);
stream.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(objResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
// Close and clean up the StreamReader
streamReader.Close();
}
}
catch (Exception e)
{
result = "Exception: " + e.Message;
}
return result;
}
help me to get rid from 403 forbidden error.
Use the following.
I have tested it and it's working fine in my case.
// Grab Certificate
X509Certificate2 cert2 = new X509Certificate2(
AppDomain.CurrentDomain.BaseDirectory + "CertificateName.p12",
CertificatePasswordHere,
X509KeyStorageFlags.MachineKeySet);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://adfapi.adftest.rightmove.com/v1/property/sendpropertydetails");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ClientCertificates.Clear();
httpWebRequest.ClientCertificates.Add(cert2);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

Windows form application wont work on another PC

I created an windows form application that goes to a website and does a HTTPwebrequest POST and then displays the result in a webbrowser. I tested it on the computer that I wrote the program on and it works exactly like it should. However when I get the .exe file from the bin folder along with htmlagilitypack.dll and run a test on another computer, it does the POST data but web page that shows up in broswer is just the default login page. I have looked at it on fiddler and it seems like the cookies aren't getting set to the webbrowser. How can I fix this? I have also compiled the program in release mode and transferred the files in the release folder and its the same result.
On the program I used this to set the cookie for the browser.
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetSetCookie(string lpszUrlName, string lpszCookieName, string lpszCookieData);
Does it have to do something with that dll file?
Edit: I have made sure both computer has 4.5 NET installed.
//get the cookie first
CookieCollection cookies = new CookieCollection();
CookieContainer cookiecontainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com" + url);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//get the auth token
using (StreamReader authreader = new StreamReader(request.GetResponse().GetResponseStream()))
{
source = authreader.ReadToEnd();
}
//need the auth token
string token = Regex.Match(source, "authenticity_token.+?value=\"(.+?)\"").Groups[1].Value;
//need the POST url
string action = Regex.Match(source, "UTF-8.+?action=\"(.+?)\"").Groups[1].Value;
//get the reponse from the server and save the cookies from the first request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
response.Close();
string formparam = string.Format("utf8=%E2%9C%93&authenticity_token={0}&size={1}&commit=add to cart", token, sizechart[0]);
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com"+ action);
webreq.CookieContainer = new CookieContainer();
webreq.CookieContainer = request.CookieContainer;
//webreq.CookieContainer.Add(cookies); //recover the cookie first request
webreq.Method = "POST"; //set a POST method
webreq.Referer = "http://www.supremenewyork.com" + url;
webreq.ContentType = "application/x-www-form-urlencoded";
webreq.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
webreq.KeepAlive = true;
webreq.AllowAutoRedirect = true;
byte[] bytes = Encoding.UTF8.GetBytes(formparam);
webreq.ContentLength = bytes.Length;
//write
Stream postdata = webreq.GetRequestStream(); //open connection
postdata.Write(bytes, 0, bytes.Length); //send the data
postdata.Close();
//get the final response from the server
HttpWebResponse resp = (HttpWebResponse)webreq.GetResponse();
cookies = resp.Cookies;
response.Close();
//Stream answer = resp.GetResponseStream();
//StreamReader _answer = new StreamReader(webreq.GetResponse().GetResponseStream());
//string reply = _answer.ReadToEnd();
//need to check if item has been added to cart
//richTextBox1.Text = reply;
//check if item has been added to cart
HttpWebRequest webreq2 = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com/shop/cart");
//webreq2.CookieContainer = new CookieContainer();
webreq2.CookieContainer = webreq.CookieContainer;
HttpWebResponse resp2 = (HttpWebResponse)webreq2.GetResponse();
Stream answer2 = resp2.GetResponseStream();
StreamReader _answer2 = new StreamReader(webreq2.GetResponse().GetResponseStream());
string reply2 = _answer2.ReadToEnd();
string item = textBoxkeyword.Text;
string color = textBoxcolor.Text.ToLower();
if(reply2.Contains(color))
{
//proceed to check out
//update user
appendtext(nDateTime + item + " " + color + " added to cart" );
appendtext(nDateTime + "Please check out the item");
HttpWebRequest webreq3 = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com/checkout");
//webreq3.CookieContainer = new CookieContainer();
webreq3.CookieContainer = webreq2.CookieContainer;
HttpWebResponse resp3 = (HttpWebResponse)webreq3.GetResponse();
//webBrowser1.ScriptErrorsSuppressed = false;
//RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\Main", true);
//RegKey.SetValue("Display Inline Images", "yes");
string cookie_string = "";
foreach (Cookie cook in resp3.Cookies)
{
cookie_string += cook.ToString() + ";";
InternetSetCookie("http://www.supremenewyork.com/checkout", cook.Name, cook.Value);
}
webBrowser1.Navigate("http://www.supremenewyork.com/checkout");
}
Edit2: added all the code

HttpWebRequest get 404 page only when using POST mode

First of all: I know this has been asked over 100 times, but most of these questions were eigher caused by timeout problems, by incorrect Url or by foregetting to close a stream (and belive me, I tried ALL the samples and none of them worked).
So, now to my question: in my Windows Phone app I'm using the HttpWebRequest to POST some data to a php web service. That service should then save the data in some directories, but to simplify it, at the moment, it only echos "hello".
But when I use the following code, I always get a 404 complete with an apache 404 html document. Therefor I think I can exclude the possibility of a timeout. It seems like the request reaches the server, but for some reason, a 404 is returned. But what really makes me be surprised is, if I use a get request, everything works fine. So here is my code:
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp(server + "getfeaturedpicture.php?randomparameter="+ Environment.TickCount);
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0";
webRequest.Method = "POST";
webRequest.ContentType = "text/plain; charset=utf-8";
StreamWriter writer = new StreamWriter(await Task.Factory.FromAsync<Stream>(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null));
writer.Write(Encoding.UTF8.GetBytes("filter=" + Uri.EscapeDataString(filterML)));
writer.Close();
webRequest.BeginGetResponse(new AsyncCallback((res) =>
{
string strg = getResponseString(res);
Stator.mainPage.Dispatcher.BeginInvoke(() => { MessageBox.Show(strg); });
}), webRequest);
Although I don't think this is the reason, here's the source of getResponseString:
public static string getResponseString(IAsyncResult asyncResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse webResponse;
try
{
webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
}
catch (WebException ex)
{
webResponse = ex.Response as HttpWebResponse;
}
MemoryStream tempStream = new MemoryStream();
webResponse.GetResponseStream().CopyTo(tempStream);
tempStream.Position = 0;
webResponse.Close();
return new StreamReader(tempStream).ReadToEnd();
}
This is tested code work fine in Post method with some body. May this gives you an idea.
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/plain; charset=utf-8";
req.BeginGetRequestStream(SendRequest, req);
}
catch (WebException)
{
}
}
//Get Response and write body
private void SendRequest(IAsyncResult asyncResult)
{
string str = "test";
string Data = "data=" + str;
HttpWebRequest req= (HttpWebRequest)asyncResult.AsyncState;
byte[] postBytes = Encoding.UTF8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
request.BeginGetResponse(SendResponse, req);
}
//Get Response string
private void SendResponse(IAsyncResult asyncResult)
{
try
{
MemoryStream ms;
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
HttpWebResponse httpResponse = (HttpWebResponse)response;
string _responestring = string.Empty;
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
_responestring = reader.ReadToEnd();
}
}
catch (WebException)
{
}
}
I would suggest you to use RestSharp for your POST requests in windows phone. I am making an app for a startup and i faced lots of problems while using a similar code as yours. heres an example of a post request using RestSharp. You see, instead of using 3 functions it can be done in a more concise form. Also the response can be handled efficiently. You can get RestSharp from Nuget.
RestRequest request = new RestRequest("your url", Method.POST);
request.AddParameter("key", value);
RestClient restClient = new RestClient();
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
StoryBoard2.Begin();
string result = response.Content;
if (result.Equals("success"))
message.Text = "Review submitted successfully!";
else
message.Text = "Review could not be submitted.";
indicator.IsRunning = false;
}
else
{
StoryBoard2.Begin();
message.Text = "Review could not be submitted.";
}
});
It turned out the problem was on the server-side: it tried it on the server of a friend and it worked fine, there. I'll contact the support of the hoster and provide details as soon as I get a response.

Categories