My question is rather simple, but I can't find any information about this on the internet.
I am developing a windows phone application and I want to use the web api (from MVC 4) to get, set, and update.
I already made all the GET methods and they work fine. My question is: How can I perform a POST from a url (and add data to my database)?
Something like this: http://someurl.com/api/post/username/parameter1/parameter2
Is this even possible? And otherwise how else can I resolve this problem?
Simply use RestSharp for all your WebApi work in Windows Phone.
Believe me when I say that it will save you development time!
(To say the truth, I almost never use WebRequest directly in my apps, and just go ahead with RestSharp...)
There are two alternatives:
WebClient.UploadStringAsync
WebClient client = new WebClient();
client.UploadStringCompleted += OnUploadStringCompleted;
client.UploadStringAsync(new Uri("http://someurl.com/api/post/username/parameter1/parameter2", UriKind.Absolute), "Data to upload goes here");
or
HttpWebRequest.BeginGetRequestStream
There's a complete example on this MSDN page.
Hope that helps!
Related
I'm coming to .net web api from a JavaScript background, and I'm trying to make a proxy to help with a cross domain JSON request. I'm GETing from a server I don't control the source code for, so I can't configure CORS directly. Likewise, it doesn't speak JSONP.
So two questions as I try to get my head around Web API:
1) Is Httpclient the right tool for this job? (if not, what is?)
2) If httpclient IS the right tool, what is an absolute bare bones httpclient config so I can test this out? Not worried about throwing exceptions or anything else other than just GETing API data and feeding it to a jQuery client.
I guess one other piece of information that would be nice would be building username / password authentication into the http request.
Any help is much appreciated, as are links to any good blogs / tutorials / etc that might help as an introduction to this sort of thing. I've watched several today alone, and I'm still not able to get a basic http request going on the server side without resorting to cutting / pasting other people's code.
Thanks in advance!
** EDIT - To make this question a bit more clear, what I'm trying to test is 1) Can the proxy connect to the third party server, which involves authentication via a username and password 2) Can the proxy then respond to the jQuery client request with the JSON data it received from the third party server.
Thanks to all who have taken the time to respond.
HttpClient seems to be ok in this job.
About the minimal config- it depends on what the third party expects. In most cases would work out-of-the-box, but there always may be some minor tweaks like headers and/or auth code.
I have just found some blog entry where some author shows how to test such a proxy and shows the proxy code too. Please see: http://www.davidbreyer.com/programming/2014/10/11/create-fake-responses-to-rest-service-calls-in-c/
You can find info about sending credentials here: How to use credentials in HttpClient in c#?
HTH
EDIT:
this sample code should work (copied from blog above and modified):
public class Proxy
{
public async Task<ExampleDto> GetExample(int id)
{
var client=new HttpClient();
//set some auth here
//set other headers
var response = client.GetAsync(
string.Format("/api/restserviceexample/{0}", id))
.Result.Content.ReadAsAsync<ExampleDto>();
return await response;
}
}
It's so simple that you can just run it and see if the other server responds. If not, you can play with headers - since all the session info and user auth info are sent using ookies and/or headers, all you have to do is to see how it's made with regular browser and then fake it on the server. Probably best tool for this job will be Fiddler.
However - there is one thing to consider. If the other service has special method for authorization (other than passing credentials with each request) the whole thing becomes tricky, since your proxy should perform authorization using their service, then store their auth cookie on the server or propagate them to the browser and attach them with all next requests.
First, you don't need ASP.NET with C# if you really want minimal.
.NET has great http handling without ASP. Check out classes like HttpListener, HttpListenerContext, HttpListenerRequest, etc... Yes, you'll have to write some boilerplate as your application, but these classes are pretty good.
See among others:
http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=599978
Second, if you want user & password, I'd checkout using oauth authentication so you don't have to deal with them directly. Google Plus, Windows Live, Facebook, etc... all have similar OAuth 2.0 APIs for that. See among others:
http://msdn.microsoft.com/en-us/library/dn659750.aspx
https://developers.google.com/+/web/signin/server-side-flow
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2
I am trying to do a web search from within a C# app. I am currently using this code that gets an error.
WebRequest http = HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)http.GetResponse(); //error occurs here
I keep getting "The remote name could not be resolved: 'search.yahooapis.com'".
Here is the code for the url parameter:
StringBuilder url = new StringBuilder();
url.Append("http://search.yahooapis.com/WebSearchService/V1/webSearch?");
url.Append("appid=YahooDemo&results=100&query=");
url.Append(HttpUtility.UrlEncode(searchFor));
The problem, I think, is that I need an API key from Yahoo in place of 'YahooDemo' in the above code. I went to http://developer.apps.yahoo.com/projects and got an application ID but when I enter it it still does not work? I think the problem is I did not know what to put in the Yahoo project for Application URL and Callback Domain - I don't really know what this even means? I am happy to use other providers such as Google or Bing if this makes it easier. But I am new to C# so really need detailed but simple explanations to understand what I need to do. I am a bit lost. In the end I basically just want to do a web search from my C# program to look for key words, so if their is an easier way to do this I am all for it. Any suggestions?
Ok, installed Visual Web Developer 2008, Created a Website as ASP.net (C# Language), than added a Service to it via the following URL: http://ws.idssasp.com/members.asmx?wsdl and after hitting Go, looks like this (I change the namespace to ServiceMembers):
Now it looks like this:
If I than go to Default.aspx.cs file, How do I use this on Page Load? I want something to be outputted from the Service on Page Load, ofcourse, will need to call something else via a button, but really just need a way to get anything from this service to be outputted... How to do this?
Looking here: http://ws.idssasp.com/members.asmx there are a bunch of methods that resemble the pic above, but how to use them anywhere? When I try to do Response.Write(ServiceMembers.GetCategoryListResponse); if gives error that this is a Type and can not be used in that way. How do I use anything here?
Also, I will need to pass a Username and Password into the initial SOAP POST to that URL (which I have), before I can get anything back as a Response, but how? Looks like I should use ServiceMembers.AuthorizeHeader somehow? But how? Looking at the Request XML from this page here for GetCategoryList, has this listed in the XML:
<soap:Header>
<AuthorizeHeader xmlns="http://ws.idssasp.com/Members.asmx">
<UserName>string</UserName>
<Password>string</Password>
</AuthorizeHeader>
</soap:Header>
But how to do this via code to the server? Unknown!
I don't see GetCategoryList Method as an option for ServiceMembers namespace anywhere, but there is GetCategoryListRequest Type and GetCategoryListResponse Type as options for ServiceMembers via the last pic. How do I invoke Methods of a Service? How do I use any of this for this step in the process? I have read so many tutorials on this, but nothing that I've seen explains how to do this without error of some sort, or different situations than mine.
Can anyone start me out with just simple code on outputting anything from this Web Service? Anything at all? Everyone is saying to use Visual Web Developer as it will do the Bulk of the work for you, but no one is explaining how to use any Web Service that you install. Seems that they only explain on how to use Specific things in Web Services, it's like they aren't teaching you to fish in an ocean of fish, but instead setting you up to fail, with a fish in a bucket that you are sure to catch.
What is the next step here? I didn't create this Web Service, and I don't know how to use it in the ASP.NET Website either.
The GetCategoryList method is in MembersSoapClient class and you need to create an instance of MembersSoapClient to use GetCategoryList. Try this in your Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
AuthorizeHeader authorizeHeader = new AuthorizeHeader();
authorizeHeader.UserName = "yourusername";
authorizeHeader.Password = "yourpassword";
MembersSoapClient client = new MembersSoapClient();
Category[] categories = client.GetCategoryList(authorizeHeader);
}
I've been searching around now for quite a while and can't get any straight answer as to how to call a java servlet from the windows phone 7 API? I've read about 'WebClient' and 'HttpWebRequest' but the implementations seem to differ for normal C# and the windows phone.
The method (or rather empty shell) I have looks like this:
public Login(string userName, password){
string servletUrl = "http://172.12.5.35:8080/SomeService/login?u="+userName+"&p="+password;
//Somehow to call the servlet>>
}
I'm a Java coder, although the syntax is almost identical, I've been thrown in the deep end here coding for the windows phone.
Also maybe worth mentioning that the servlet returns JSON. How does one handle that in C#?
Thanks in advance for any push in the right direction!
My Attempt using HttpWebRequest:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(servletUrl);
HttpWebResponse response = (HttpWebRequest)request.BeginGetResponse();
But I see that 'BeginGetResponse()' takes 2 arguments namely AsyncCallback & object state. What are these two arguments and what would mine be in this case?
I've read about 'WebClient' and 'HttpWebRequest' but the implementations seem to differ for normal C# and the windows phone.
Well, it doesn't support the synchronous API, that's all. There are lots of aspects of the WP7 API (and Silverlight in general) which are subsets of the full desktop framework. You need to think asynchronously - you'll start making the request, with a callback to fire when you get a response.
Note that this has nothing to do with the implementation of the web server you're talking to. You'd write the same code whether you're talking to a Java servlet, a Rails app, whatever.
Also maybe worth mentioning that the servlet returns JSON. How does one handle that in C#?
Personally I like Json.NET and have used that successfully on Windows Phone 7.
Here is the sample code which makes a web request to get JSON data
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/public_timeline.json", UriKind.Absolute));
and the DownloadStringCompleted handler is,
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var jsonResponse= e.Result; // To check whether the json response is obtained or not
var jsonData = JsonConvert.DeserializeObject<SomeObject>(e.Result);
}
In the above code, SomeObject is the Class to which you want to convert the JSON data to.
Additionally, paste your json URL or json Data in this link to generate the suitable class for you.
I use Process.Start("firefox.exe", "http://localhost/page.aspx");
And how i can know page fails or no?
OR
How to know via HttpWebRequest, HttpWebResponse page fails or not?
When i use
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("somepage.aspx");
HttpWebResponse loWebResponse = (HttpWebResponse)myReq.GetResponse();
Console.Write("{0},{1}",loWebResponse.StatusCode, loWebResponse.StatusDescription);
how can I return error details?
Not need additional plugins and frameworks. I want to choose this problem only by .net
Any Idea please
Use Watin to automate firefox instead of Process.Start. Its a browser automation framework that will let you monitor what is happening properly.
http://watin.sourceforge.net/
edit: see also Google Webdriver http://google-opensource.blogspot.com/2009/05/introducing-webdriver.html
If you are spawning a child-process, it is quite hard and you'd probably need to use each browser's specific API (it won't be the same between FF and IE, for example).
It doesn't help that in many cases the exe detects an existing instance and forwards the request there (so you can't trust the exit-code, since the page hasn't even been requested in the right exe yet).
Personally, I try to avoid assuming any particular browser for this scenario; just launch the url:
Process.Start("http://somesite.com");
This will use the user's default browser. You have to hope it appears though - you can't (reliably and robustly) check that externally without lots of work.
One other option is to read the data yourself (WebClient.Download*) - but this may have issues with complex cookies, login, user-agent awareness, etc.
Use HttpWebRequest class or WebClient class to check this. I don't think Process.Start will return something if the URL not exists.
Don't start the page in this form. Instead, create a local http://localhost:<port>/wrapper.html which loads http://localhost/page.aspx and then either http://localhost:<port>/pass.html or http://localhost:<port>/fail.html. localhost: is a trivial HTTP server interface implemented by your app.
The idea is that Javascript gives you an API inside the browser, which is far more standard than the APIs on the outside of browsers. Since the Javascript on wrapper.html comes from the same server and even port as the subsequent resources, this should satisfy the same-origin policies in current browsers.