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.
Related
I've searched some time, looking for easy way to connect with some other sites WebAPI. There are some solutions, but they are made in very complicated way.
What I want to do:
Connect with server using URL adress
Provide login and password to get some data
Get data as JSON/XML
Save this data in an "easy-to-read" way. I mean: save it to C# variable which could be easy to modify.
Currently, API that I want to work with is Bing Search, but I'm looking for some universal way. I found an example, but it doesn't work for me and in my app I can't use this class: "DataServiceQuery" because it doesn't exsist.
How do you usually do it? Do you have your favourite solutions? Are there some universal ways or it depends on type of API that you work with?
I'm currently working on .NET MVC app (in case it could make any difference)
From server side
You can use that like below.
// Create an HttpClient instance
HttpClient client = new HttpClient();
// Send a request asynchronously continue when complete
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
var result = readTask.Result
//Do something with the result
});
});
You can see example on following link.
https://code.msdn.microsoft.com/Introduction-to-HttpClient-4a2d9cee
For JavaScirpt:
You could use jQuery and WebAPI both together to do your stuff.
There are few steps to it.
Call web api with Ajax jquery call.
Get reponse in JSON
Write javascript code to manipulate that response and do your stuff.
This is the easiest way.
See following link for reference:
http://www.codeproject.com/Articles/424461/Implementing-Consuming-ASP-NET-WEB-API-from-JQuery
It entirely depends on the type of API you want to use. From a .Net point of view, there could be .Net 2 Web Services, WCF Services and Web API Services.
Web APIs today are following the REST standard and RMM. Some APIs need API Keys provided as url parameters, others require you to put in request's header. Even some more robust APIs, use authentication schemes such as OAuth 2. And some companies have devised their own standards and conventions.
So, the short answer is that there is no universal way. The long answer comes from documentation of each API and differs from one to another.
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!
I am creating a PHP website connected to a MySQL database. Next I will need to write a C# desktop app that will use the same DB. Unfortunately I cannot connect to the DB directly from a remote location and my hosting company won't allow SSH neither.
So what options do I have? If the hosting company supported .NET, it wouldn't be a problem, but I'm not that experienced with PHP. Will I have to write a PHP service (SOAP?) and then consume it in my desktop app? Also, how do I communicate with server from the desktop app?
Any help appreciated!
Depending on security requirement, could you write a generic SQL executing page in PHP, that took the SQL as a String parameter, and returned the results as an array of Strings (Might need some meta data too or something)?
Other than that the only thing I can think of is a web service of some kind.
Also SOAP can work both ways, you can read and write from the C# app, no need to write a WebService on both ends, unless you need to notify your c# app about something from the server (In which case you could always try frequent polling from the c# app)
Best option would be creating a set of RESTful services in your PHP site.
One of most important things to take in account is REST is more configuration by convention, and there's no need of things like SOAP which may be an absolute overkill for your solution.
You just send JSON from PHP and .NET Windows application will parse it as a CLR object.
A sample scenario would be:
Service operation: http://yourdomainhere.com/API/Message/34894
** This returns something like { "text": "hello world" }
.NET client receives this JSON and using a JSON parser like Newton JSON parser, you'd be doing this:
MessageDto dto = JsonConvert.DeserializeObject([JSON received from the service call]);
MessageBox.Show(dto.Text); // This will show "hello world"
It's just a very simple example, but it'd give you an idea of what's next.
You can query your REST API using WebRequest/WebResponse .NET BCL classes.
PHP only needs to send a web response including your JSON in the output stream, that's all. No SOAP, no XML, no complication. Keep it simple.
I think the following link will be of helpful to you!
Developing SOAP Web Services with PHP/C#
What you can do is providing some PHP-wrappers which you can access from your C# code. As an example you can use this discussion, regarding C# / PHP communication.
Basically you can send a HTTP request to PHP and retrieve it's return value with C#. PHP would then perform the DB requests. If you're using AJAX on the Website it should be easy using the same communication interfaces.
this is the first paragraph of Matt Fellows answer.
But in what form do you send the data back to the application in?
Maybe JSON?
PHP webpage
<?php
$host = "host.host.com";
$user = "XXXXX";
$password = "XXXX";//plaintext :)
$connection = mysql_connect($host, $user, $password);
$database = "XXXXX";
$syntax = $_GET['syntax']; //www.example.com/help.php?syntax=DROP%20TABLE%20XXX
$result = mysql_query($syntax);
//somehow output the $result in C# readable form
?>
I've built a simple C# app (.Net 4.0 + WPF) which can send and receive JSON messages via TCP sockets.
As a next step, it should be possible that JavaScript apps on websites and PHP scripts can send and receive JSON messages to/from my app. Is that possible?
Since JS/PHP will use stateless HTTP connections, how should a request to my app work, for example, should the JS/PHP apps send a JSON message to my app and my app response (HTTP response) with a JSON message? Is that even possible? And should I use GET or POST method to send the JSON messages to/from my app?
Hope my questions do not cause too much confusion ;-) I but I appreciate every tip, clarification or feedback you can give me.
Mike
You can accomplish this via a .NET web service using special JSON directives on the web method, e.g.
[ScriptMethod(UseHttpGet = true, ResponseFormat=ResponseFormat.Json)]
public string DoSomething(string param1, int param2)
{
// Do Something
}
When the ResponseFormat.Json property is specified, the data returned will be serialized into the appropriate JSON format. Also note, in order to recieve a true JSON response, you'll need to set your content-type to "application/json" from the requesting application. Otherwise, the method will attempt to wrap the response in XML.
Also, I am enabling a HttpGet on this method so that you can post via a query string to the method, e.g.
http://www.example.com/service.asmx?param1='Hello'¶m2=1;
I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started.
I've found some information on the WebRequest class in C# (specifically from here) but before I start diving into it, I wondered if this was the right tool for the job.
I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.
WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like:
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://mysite.com/index.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "var=value1&var2=value2";
req.ContentLength = postData.Length;
StreamWriter stOut = new
StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
stOut.Write(postData);
stOut.Close();
Similarly you can read the response back by using the GetResponse method which will allow you to read the resultant response stream and do whatever else you need to do. You can find more info on the class at:
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
WebClient is sometimes easier to use than WebRequest. You may want to take a look at it.
For JSON deserialization you are going to want to look at the JavaScriptSerializer class.
WebClient example:
using (WebClient client = new WebClient ())
{
//manipulate request headers (optional)
client.Headers.Add (HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
//execute request and read response as string to console
using (StreamReader reader = new StreamReader(client.OpenRead(targetUri)))
{
string s = reader.ReadToEnd ();
Console.WriteLine (s);
}
}
Marked as wiki in case someone wants to update the code
When it comes to POSTing data to a web site, System.Net.HttpWebRequest (the HTTP-specific implementation of WebRequest) is a perfectly decent solution. It supports SSL, async requests and a bunch of other goodies, and is well-documented on MSDN.
The payload can be anything: data in JSON format or whatever -- as long as you set the ContentType property to something the server expects and understands (most likely application/json, text/json or text/x-json), all will be fine.
One potential issue when using HttpWebRequest from a system service: since it uses the IE proxy and credential information, default behavior may be a bit strange when running as the LOCALSYSTEM user (or basically any account that doesn't log on interactively on a regular basis). Setting the Proxy and Authentication properties to Nothing (or, as you C# folks prefer to call it, null, I guess) should avoid that.
I have used WebRequest for interacting with websites. It is the right 'tool'
I can't comment on the JSON aspect of your question.
The currently highest rated answer is helpful, but it doesn't send or receive JSON.
Here is an example that uses JSON for both sending and receiving:
How to post json object in web service
And here is the StackOverflow question that helped me most to solve this problem:
Problems sending and receiving JSON between ASP.net web service and ASP.Net web client
And here is another related question:
json call with C#
To convert from instance object to json formatted string and vice-versa, try out Json.NET:
http://json.codeplex.com/
I am currently using it for a project and it's easy to learn and work with and offers some flexibility in terms of serializing and custom type converters. It also supports a LINQ syntax for querying json input.
in 3.5 there is a built-in jsonserializer. The webrequest is the right class your looking for.
A few examples:
Link
http://dev.aol.com/blog/markdeveloper/ShareFileWithNETFramework
Link