Post with WebRequest - c#

I am trying to post to google so I can log into Google Reader and download subscription list, but I am unable to find a way to post to google in the windows 7 phone sdk, does anyone have an example on how to do this?
*Edit: Sorry wasn't very clear I am trying use the POST method, to submit an email and password to google login and retrieve a sid. I have used WebClient and HttpWebRequest but all the examples I have seen to send post data, the api calls are not in the windows 7 phone sdk.

I don't know anything about the Google API you're trying to use, but if all you need is to send a POST request, you can certainly do that with WebClient or HttpWebRequest. With WebClient, you can use either WebClient.OpenWriteAsync() or WebClient.UploadStringAsync(), the documentation is here: http://msdn.microsoft.com/en-us/library/tt0f69eh%28v=VS.95%29.aspx
With HttpWebRequest, you'll need to set the Method property to "POST". Here's a basic example:
var request = WebRequest.Create(new Uri(/* your_google_url */)) as HttpWebRequest;
request.Method = "POST";
request.BeginGetRequestStream(ar =>
{
var requestStream = request.EndGetRequestStream(ar);
using (var sw = new StreamWriter(requestStream))
{
// Write the body of your request here
}
request.BeginGetResponse(a =>
{
var response = request.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var sr = new StreamReader(responseStream))
{
// Parse the response message here
}
}, null);
}, null);
The WebClient class may be easier to use, but is less customizable. For instance, I haven't seen a way to be able to attach cookies to WebClient requests, or a way to set the Content-Type header when using WebClient.

Have you tried using RESTSharp for your Windows Phone 7 project? The latest release supports Windows Phone 7 and I have had no issues working with popular REST APIs with it. In your particular case where you are trying to use the Google Reader API, this article by Luke Lowry can possibly help.

Not sure what you've already used, but have you tried WebClient?
WebClient web = new WebClient();
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
CodeHereToHandleSuccess();
else
CodeHereToHandleError(e.Error);
};
web.DownloadStringAsync(new Uri(theURLYoureTryingToUse));
There's also WebRequest to look at too, that might work for what you're doing.
Edit: As for your "POST" edit, webclient lets you do post:
web.OpenWriteAsync(new Uri(theURLYoureTryingToUse), "POST");
you also then have to add an OpenWriteCompleted handler.
not sure exactly what you're doing, so you'll need to add more info to your question.

Related

C# WebRequest timeout on second call

The first time I call this function everything works perfect.
When I call it the second time I get an exception Host is not responding correclty
I tried everything for hours but I dont get it to work.
Is it the website or is something wrong with my code?
string url = "https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp";
string website = "";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
httpRequest.Timeout = 5000;
using (var response = (HttpWebResponse)httpRequest.GetResponse())
{
using (StreamReader Reader = new StreamReader(response.GetResponseStream()))
{
website = Reader.ReadToEnd();
}
}
httpRequest.Abort();
Please, on every question that you are going to do here, try to put as maximum of details as possible. It will become easier for us to help you on your problems. Especially the exceptions that you are having doing the development.
About your code, the implementation of that is not recommended for Microsoft. Looking at the docs https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest?view=netframework-4.8 there is a part that says: We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient class.
Try to change your implementation to use the class HttpClient, and see if the error is going to occur again.

Post Not Publishing to Page via FaceBook API

All I am trying to do is post to a page using the API. This task was extremely simple using Twitter; but with FaceBook, it has been very challenging.
I am using the following code:
string url = #"https://graph.facebook.com/{page_id}/feed?message=Hello&access_token={app_id}|{app_secret}";
WebClient client = new WebClient();
Stream data = client.OpenRead(url);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
Console.WriteLine(s);
It returns data like this:
{"data":[{"story":"Page updated their cover photo.","created_time":"2017-03-13T22:49:56+0000","id":"1646548358..._164741855..."}...
But, the post is never seen on the page! How can I successfully post from my app to my page?
Your request should be a POST request as the data you're getting back suggests this is a GET request.
Also you need the publish_pages permission to successfully post to a page

WebClient restful Delete

I have a simple Restful service being called from a console app so am using WebClient. I am wondering if this call for Delete is correct.
The url looks like localhost/RestService1/Person/1
using (var client = new WebClient())
{
client.UploadString(url, "DELETE", "");
}
I don't like that UploadString does not have an overload without a data parameter. The passing of an empty parameter is not sitting well with me. Is there a better method to use for a DELETE?
I could use WebRequest but I want to just use WebClient to keep it consistent.
Here is the WebRequest block
var request = WebRequest.Create(url);
request.Method = "DELETE";
var response = (HttpWebResponse)request.GetResponse();
Both blocks work fine but what is best? Or is there a better way?
The following works for me:
client.UploadValues(url, "DELETE", new NameValueCollection());
The WebClient class doesn't really lend well to restful api consumption, I've used 3rd party libraries like RestSharp in the past that are geared more towards this type of web request. I'm pretty sure RestSharp just uses HttpWebRequest under the covers, but it provides a lot of semantics that make consuming and reusing rest resources easier.
Go get the Microsoft.Net.Http client libraries http://nuget.org/packages/Microsoft.Net.Http
HttpClient is a much better client to use for working with an API.
Sorry this is my solution in vb.net i sure that anyone can translate to c#
It's very important to drop headers, i had to comment header about Accept and Content-Type and work fine..... of course I did send the token
Dim rest As WebClient = New WebClient()
rest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " & Token)
'rest.Headers.Add(HttpRequestHeader.Accept, "application/json")
'rest.Headers.Add(HttpRequestHeader.ContentType, "application/json")
result = System.Text.Encoding.UTF8.GetString(rest.UploadValues(host_api & uri, "DELETE", New NameValueCollection()))

Call to REST web service results in response of error 503 but not with a tool like Poster

I am trying to send an xml document to a REST web service. Using a tool like Poster, the call works fine (With the xml in the body of the "content"), but in my code, I get error 503 server unavailable.
Link to Poster: https://addons.mozilla.org/en-US/firefox/addon/poster/
My code is as follows (this is a test-harness so no error handling etc):
string s = "";
using (StreamReader sr = new StreamReader(#"c:\users\dev.admin\documents\visual studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\XMLFile1.xml"))
{
s = sr.ReadToEnd();
}
string url = FULL_URL_WITH_PARAMETERS; // SAME URL AS USED IN POSTER
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
string data = s;
Stream postStream = null;
using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
{
requestStream.Write(data);
}
HttpWebResponse pervasiveResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr1 = new StreamReader(pervasiveResponse.GetResponseStream(), System.Text.Encoding.Default);
string backstr = sr1.ReadToEnd();
}
else
{
throw new ArgumentNullException();
}
REST Starter Kit? WCF Web API (Glenn Block's project, now part of AppFabric int he 4.5 time frame? (although I believe there will be a standalone))? Roll your own joint?
Regardless, I think working with binary is the correct method to go. For that reason, I would start with something like this article. Not because I tried the code and think it is a great article, but merely because the article shows sending XML and I don't have time to find the client I wrote a few months ago. ;-)
If I can break free long enough to find my code, I will post a sample.
Oh, another tool you should look at is SoapUI. No, it is not just for testing SOAP, as it supports REST (and other methodologies) as well as SOAP. One nice benefit of using SoapUI is the ability to move the tests over to LoadUI and stress testing a service. If you are merely consuming services, it might not have the greatest value, of course.

What is the best way to download files via HTTP using .NET?

In one of my application I'm using the WebClient class to download files from a web server. Depending on the web server sometimes the application download millions of documents. It seems to be when there are lot of documents, performance vise the WebClient doesn't scale up well.
Also it seems to be the WebClient doesn't immediately close the connection it opened for the WebServer even after it successfully download the particular document.
I would like to know what other alternatives I have.
Update:
Also I noticed that for each and every download WebClient performs the authentication hand shake. I was expecting to see this hand shake once since my application only communicate with a single web server. Shouldn't the subsequent calls of the WebClient reuse the authentication session?
Update: My application also calls some web service methods and for these web service calls it seems to authentication session is reused. Also I'm using WCF to communicate with the web service.
I think you can still use "WebClient". However, you are better off using the "using" block as a good practice. This will make sure that the object is closed and is disposed off:-
using(WebClient client = new WebClient()) {
// Use client
}
I bet you are running into the default limit of 2 connections per server. Try running this code at the beginning of your program:
var cme = new System.Net.Configuration.ConnectionManagementElement();
cme.MaxConnection = 100;
System.Net.ServicePointManager.DefaultConnectionLimit = 100;
I have noticed the same behavior with the session in another project I was working on. To solve this "problem" I did use a static CookieContainer (since the session of the client is recognized by a value saved in a cookie).
public static class SomeStatics
{
private static CookieContainer _cookieContainer;
public static CookieContainer CookieContainer
{
get
{
if (_cookieContainer == null)
{
_cookieContainer = new CookieContainer();
}
return _cookieContainer;
}
}
}
public class CookieAwareWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = SomeStatics.CookieContainer;
(request as HttpWebRequest).KeepAlive = false;
}
return request;
}
}
//now the code that will download the file
using(WebClient client = new CookieAwareWebClient())
{
client.DownloadFile("http://address.com/somefile.pdf", #"c:\\temp\savedfile.pdf");
}
The code is just an example and inspired on Using CookieContainer with WebClient class and C# get rid of Connection header in WebClient.
The above code will close your connection immediately after the file is download and it will reuse the authentication.
WebClient is probably the best option. It doesn't close the connection straight away for a reason: so it can use the same connection again, without having to open a new one. If you find that it's not reusing the connection as expected, that's usually because you're not Close()ing the response from the previous request:
var request = WebRequest.Create("...");
// populate parameters
var response = request.GetResponse();
// process response
response.Close(); // <-- make sure you don't forget this!

Categories