Call restful service using button click - c#

I wish to call the get function from a button click on my web application
my code in my application is
protected void btngetbtanches_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest req = WebRequest.Create(#"http://localhost:54691/") as HttpWebRequest;
WebResponse resp = req.GetResponse();
using (Stream branchstream = resp.GetResponseStream())
{
StreamReader loResponseStream =
new StreamReader(branchstream, Encoding.UTF8);
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
resp.Close();
}
}
catch (Exception ex)
{
}
}
in my service is
[ServiceContract]
public interface IRestSerivce
{
[OperationContract]
[WebGet(UriTemplate = "Default")]
string GetBranchData();
}
}
}
get data is defined in another file in the service project. When I try to click the button some html is returned and the service is not called.
Any help would be appreciated

Your web request does not match the end point of the service:
You should try:
HttpWebRequest req = WebRequest.Create
(#"http://localhost:54691/RestSerivce/GetBranchData") as HttpWebRequest;
or at least the one which matches your routing.
You can also add the service as reference and consume it's type, which is a common approache.
You can check this answer for more details.
How to consume WCF web service through URL at run time?

Related

C# Async GetWebRequest failing to POST data

I recently wrote an async HttpWebRequest client for our application and it works fine in .NET 3.5, but on Mono it fails to correctly write the data on to the request before sending it out.
I have confirmed the problem using wireshark to sniff the outgoing packets. The HTTP request is correctly set to POST with a JSON Content Type however the Content-Length and data are 0.
I currently get one exception:
The number of bytes to be written is greater than the specified
ContentLength.
I have tried to resolve this by manually setting the ContentLength of the WebRequest and changing the way I encode the data before giving it to the stream (I have tried both a Steam and StreamWriter).
I have also stepped through the code and debug logged the variables in the async method to ensure the data is really there. It just does not appear to be getting to the WebRequest object.
Here is the relevant code:
private void StartWebRequest(string payload) {
var httpWebRequest = (HttpWebRequest)WebRequest.Create(PortMapSleuthURL);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null; // Setting this to null will save some time.
// start an asynchronous request:
httpWebRequest.BeginGetRequestStream(GetRequestStreamCallback, new object[] {httpWebRequest, payload});
try {
// Send the request and response callback:
httpWebRequest.BeginGetResponse(FinishPortTestWebRequest, httpWebRequest);
} catch (Exception e) {
Console.WriteLine(e.Message);
PortTestException();
}
}
private void GetRequestStreamCallback(IAsyncResult asyncResult) {
try {
object[] args = (object[])asyncResult.AsyncState;
string payload = (string)args[1];
HttpWebRequest request = (HttpWebRequest)args[0];
//StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(asyncResult), new UTF8Encoding(false));
StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(asyncResult), Encoding.UTF8);
// Write to the request stream.
streamWriter.Write(payload);
streamWriter.Flush();
streamWriter.Close();
} catch (Exception e) {
Console.WriteLine(e.Message);
PortTestException();
}
}
I don't think you are supposed to call BeginGetResponse before EndGetRequestStream. That is, I would move that into the GetRequestStreamCallback. This is how the example on msdn works too.

how to display the content of given url in window application with c#

I want to get the http request header and also the post data from a given URL.... how to do that?.... I have to display http request header, http response header, content of a given url and post data...
Below is my code for that....
private void button1_Click(object sender, EventArgs e)
{
try
{
string url = txtUrl.Text;
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse Response = (HttpWebResponse)WebRequestObject.GetResponse();
HttpStatusCode code = Response.StatusCode;
txtStatus.Text = code.ToString();
txtResponse.Text = Response.Headers.ToString();
// Open data stream:
Stream WebStream = Response.GetResponseStream();
// Create reader object:
StreamReader Reader = new StreamReader(WebStream);
// Read the entire stream content:
string PageContent = Reader.ReadToEnd();
// Cleanup
Reader.Close();
WebStream.Close();
Response.Close();
txtContent.Text = PageContent;
// var request = WebRequest.Create("http://www.livescore.com ");
//var response = request.GetResponse();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
But how to get post data and http request header that i dont know...pls help
It's not very clear what you are trying to accomplish with mixed references to GET, POST, and request and response headers.
If you can make the request you want in a browser and use Fiddler to intercept it, you can use the Fiddler add-on Request-To-Code to generate C# code that will perform the request. The generated code would probably be a good place for you to start - from something that works and with which you can further tinker.
Fiddler is a great way to learn more about HTTP.

C# Console/Server access to web site

I am working on a C# project where I need to get data from a secured web site that does not have an API or web services. My plan is to login, get to the page I need, and parse out the HTML to get to the data bits I need to log to a database. Right now I'm testing with a console app, but eventually this will be converted to an Azure Service bus application.
In order to get to anything, you have to login at their login.cfm page, which means I need to load the username and password input controls on the page and click the submit button. Then navigate to the page I need to parse.
Since I don't have a 'browser' to parse for controls, I am trying to use various C# .NET classes to get to the page, set the username and password, and click submit, but nothing seems to work.
Any examples I can look at, or .NET classes I should be reviewing that were designed for this sort of project?
Thanks!
Use the WebClient class in System.Net
For persistence of session cookie you'll have to make a custom WebClient class.
#region webclient with cookies
public class WebClientX : WebClient
{
public CookieContainer cookies = new CookieContainer();
protected override WebRequest GetWebRequest(Uri location)
{
WebRequest req = base.GetWebRequest(location);
if (req is HttpWebRequest)
(req as HttpWebRequest).CookieContainer = cookies;
return req;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse res = base.GetWebResponse(request);
if (res is HttpWebResponse)
cookies.Add((res as HttpWebResponse).Cookies);
return res;
}
}
#endregion
Use a browser add-on like FireBug or the development tools built into Chrome to get the HTTP POST data being sent when you submit a form. Send those POSTs using the WebClientX class and parse the response HTML.
The fastest way to parse HTML when you already know the format is using a simple Regex.Match. So you'd go through the actions in your browser using the development tools to record your POSTs, URLs and HTML content then you'll perform the same tasks using the WebClientX.
Ok, so here is the complete Code to login to one page, then read from a 2nd page after the login.
class Program
{
static void Main(string[] args)
{
string uriString = "http://www.remotesite.com/login.cfm";
// Create a new WebClient instance.
WebClientX myWebClient = new WebClientX();
// Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL.
NameValueCollection myNameValueCollection = new NameValueCollection();
// Add necessary parameter/value pairs to the name/value container.
myNameValueCollection.Add("userid", "myname");
myNameValueCollection.Add("mypassword", "mypassword");
Console.WriteLine("\nUploading to {0} ...", uriString);
// 'The Upload(String,NameValueCollection)' implicitly method sets HTTP POST as the request method.
byte[] responseArray = myWebClient.UploadValues(uriString, myNameValueCollection);
// Decode and display the response.
Console.WriteLine("\nResponse received was :\n{0}", Encoding.ASCII.GetString(responseArray));
Console.WriteLine("\n\n\n pausing...");
Console.ReadKey();
// Go to 2nd page on the site to get additional data
Stream myStream = myWebClient.OpenRead("https://www.remotesite.com/status_results.cfm?t=8&prog=d");
Console.WriteLine("\nDisplaying Data :\n");
StreamReader sr = new StreamReader(myStream);
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(myStream, System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line + "\r\n");
}
}
using (StreamWriter outfile = new StreamWriter(#"Logfile1.txt"))
{
outfile.Write(sb.ToString());
}
Console.WriteLine(sb.ToString());
Console.WriteLine("\n\n\n pausing...");
Console.ReadKey();
}
}
public class WebClientX : WebClient
{
public CookieContainer cookies = new CookieContainer();
protected override WebRequest GetWebRequest(Uri location)
// public override WebRequest GetWebRequest(Uri location)
{
WebRequest req = base.GetWebRequest(location);
if (req is HttpWebRequest)
(req as HttpWebRequest).CookieContainer = cookies;
return req;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse res = base.GetWebResponse(request);
if (res is HttpWebResponse)
cookies.Add((res as HttpWebResponse).Cookies);
return res;
}
}

HttpWebRequest Exception Handling

I am making an asyncronous HttpWebRequest and if that fails, I want to call a backup web service. Like so:
public void CallService1()
{
HttpWebRequest request = HttpWebRequest.Create("http://MyFirstWebService")
request.BeginGetResponse(this.CallService1Completed, request);
}
public void CallService1Completed(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
{
using (Stream responseStream = response.GetResponseStream())
{
// Use Data
}
}
}
catch (WebException webException)
{
if (?????)
{
CallBackupService2();
}
}
}
Bearing in mind that this is a mobile applications where you may not always have an internet connection. I do not want to call the backup service if there is no internet connection. I only want to call the backup service if the first service is down for some reason. What would I put in the 'IF' statement above.
It can be implemented like:
if (NetworkInterface.GetIsNetworkAvailable())
{
CallBackupService2();
}

How to past post an XML stream to a wcf http rest service using an HttpWebRequest

I am trying to send an HTTPWebRequest POST XML data to my WCF service.
However when setting a breakpoint in my service, it is hit, but my widgetStream is empty when I try to read it. Even if I read it from a StreamReader.
Does anyone know what I am doing wrong?
My WCF service looks like this:
[WebInvoke(UriTemplate = "widgets", Method = "POST"]
public void CreateWidget(Stream widgetStream)
{
try
{
XElement e = XElement.Load(widgeStream);
//...
}
catch (Exception ex)
throw;
}
}
My client is trying to connect and post an XML resource to an HTTP URL like so:
public static void CreateWidget(Widget myWidget)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:29858/myservice/widgets");
request.Method = "POST";
request.ContentType = "text/xml";
string xml = myWidget.ToXML().ToString();
request.ContentLength = xml.Length;
Stream s = request.GetRequestStream();
StreamWriter sr = new StreamWriter(s);
sr.Write(xml);
sr.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
If anyone could please help that would be appreciated!
[WebInvoke(UriTemplate = "widgets", Method = "POST", RequestFormat=WebMessageFormat.Xml, BodyStyle=WebMessageBodyStyle.Bare]
[XmlSerializerFormat]
public void CreateWidget(XElement widget){...}
Try this on your service. I just ran into a similar issue this week. I haven't tried using the HTTPWebRequest object but I can post raw XML to the service using Fiddler.
You might need to change Content-Type on the client to "application/xml" rather than "text/xml".

Categories

Resources