Call to OData service from C# - c#

I use the code below to call an OData service (which is the working service from Odata.org) from C# and I don't get any result.The error is in the response.GetResponseStream().
Here is the error :
Length = 'stream.Length' threw an exception of type 'System.NotSupportedException'
I want to call to the service and parse the data from it, what is the simpliest way to do that?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
namespace ConsoleApplication1
{
public class Class1
{
static void Main(string[] args)
{
Class1.CreateObject();
}
private const string URL = "http://services.odata.org/OData/OData.svc/Products?$format=atom";
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/xml";
request.Accept = "application/xml";
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
}
}
}
}
}

I ran your code on my machine, and it executed fine, I was able to traverse all XML elements retrieved by the XmlTextReader.
var request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/xml";
request.Accept = "application/xml";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
var reader = new XmlTextReader(stream);
while (reader.Read())
{
Console.WriteLine(reader.Value);
}
}
}
But as #qujck suggested, take a look at HttpClient. It's much easier to use.

If you're running .NET 4.5 then take a look at HttpClient (MSDN)
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(endpoint);
Stream stream = await response
.Content.ReadAsStreamAsync().ConfigureAwait(false);
response.EnsureSuccessStatusCode();
See here and here for complete examples

Related

Rest URL consumption guidance required

I have a rest url provided by client , It looks something like www.baseurl/api// I couldn't get result if I try to consume it from console application getting error 503.
However I m able to browse it from my browser and it returns the proper json of Entity Details. Please help me with this.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp15
{
public class Class1
{
private const string URL = "www.baseurl/api/<EntityName>/<EntityID>";
static void Main(string[] args)
{
Class1.CreateObject();
}
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
}
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
}
}
}
}

c# Json Post throws 404 bad request error

I am new to JSON and C# and trying for a POST request and reading the response.
I am writing the Content Type correctly, url I am trying to send to the server is also correct. Probably my code is just incorrect and I will appreciate for any helps on this.
Below is my code but I keep getting 400 bad request.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
public class Server
{
public void ServerStart()
{
try{
string webAddr="https://localhost:61000/users/login";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"userName\" : \"laborel\", \"userPassword\" : \"dGVzdG5ldFBDMSEu\" }";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
byte[] responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
}catch(WebException ex){
Console.WriteLine(ex.Message);
System.Windows.Forms.MessageBox.Show(string.Format ("Exception Occurred: {0}",ex.Message));
}
}
}
One thing byte[] responseText = streamReader.ReadToEnd(); is not right, where I am not sure what should bet the responseText
Could some one point me out on how can we create a function which accepts the webaddress and the json string as input and returns the response text
Following would work string responseText = streamReader.ReadToEnd();

C# Console Application httpWebRequest

Im trying to create a very simple c# console application to post some data to a web api. However whatever I do I get an error on the response like:
responseText "{\"info\":{\"status\":\"failed\",\"error\":{\"code\":1000,\"message\":\"Invalid argument from request\"}}}" string
The api http://www.detrack.com/api-documentation/ is looking for a post like
https://app.detrack.com/api/v1/deliveries/view/all.json?key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&json={"date":"2014-08-29"}
I know using this in chrome advanced rest application extension returns a valid result. But When I try the same via this console code. I get an error!.
Here is the code I have in my console application.
using System;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://app.detrack.com/api/v1/deliveries/view/all.json?key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "json={\"date\":\"2014-08-28\"}";
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadKey();
}
}
}
}
Any help/guidance would be really appreciated
brendan
So I'm looking at this:
string json = "json={\"date\":\"2014-08-28\"}";
And according to the brief description on detrack that is not what you want. They're expecting valid json and that isn't. Here's what you should be considering valid json:
string json = "{\"date\":\"2014-08-28\"}";
Be warned I don't know about your escaping of quotes. I would serialize that differently; either a strongly typed class or an anonymous class. Anon would look like this:
string json = JsonConvert.DeserializeObject(new { date = "2014-08-28" });
Setting aside any concerns about time, timezones, utc, etc, that will serialize your structures correctly. Here's a scratchy program from linqpad:
void Main()
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { date = "2014-08-28"});
Console.WriteLine(json);
}
>>> {"date":"2014-08-28"}
You can try the (untested!) code below.
using System;
using System.Net;
using System.IO;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
var webAddr = "https://app.detrack.com/api/v1/deliveries/create.json";
var httpWebRequest = (HttpWebRequest) WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
string postData = "key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&json={""date"":""2014-08-28""}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
httpWebRequest.ContentLength = byteArray.Length;
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(byteArray, 0, byteArray.Length);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
MessageBox.Show(result);
}
}
}
}

POST Querystring using WebClient

I want to execute a QueryString using WebClient but using the POST Method
That is what I got so far
CODE:
using (var client = new WebClient())
{
client.QueryString.Add("somedata", "value");
client.DownloadString("uri");
}
It is working but unfortunately it is using GET not POST and the reason I want it to use POST is that I am doing a web scraping and this is how the request is made as I see in WireShark. [IT USES POST AS A METHOD BUT NO POST DATA ONLY THE QUERY STRING.]
In answer to your specific question:
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] response = client.UploadData("your url", "POST", new byte[] { });
//get the response as a string and do something with it...
string s = System.Text.Encoding.Default.GetString(response);
But using WebClient can be a PITA since it doesn't accept cookies nor allow you to set a timeout.
this will help you, use WebRequest instead of WebClient.
using System;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
class ThreadTest
{
static void Main()
{
WebRequest req = WebRequest.Create("http://www.yourDomain.com/search");
req.Proxy = null;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string reqString = "searchtextbox=webclient&searchmode=simple";
byte[] reqData = Encoding.UTF8.GetBytes(reqString);
req.ContentLength = reqData.Length;
using (Stream reqStream = req.GetRequestStream())
reqStream.Write(reqData, 0, reqData.Length);
using (WebResponse res = req.GetResponse())
using (Stream resSteam = res.GetResponseStream())
using (StreamReader sr = new StreamReader(resSteam))
File.WriteAllText("SearchResults.html", sr.ReadToEnd());
System.Diagnostics.Process.Start("SearchResults.html");
}
}

Obtain Request Token From REST API using Oauth1 in C#

As the title states, I just need help with the first part of OAuth1.0 authentication: obtaining the request token. I am doing this in a console application using C#. I have been working on this for 3 days now and I have tried numerous samples from the internet, but so far nothing works. Here is my current attempt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MCAPIClient
{
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "oauth_consumer_key", "<my consumer key>" },
{ "oauth_consumer_secret", "<my secret key>" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://app.masteryconnect.com/oauth/request_token", content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(response.Headers);
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}
}
This works beautifully when consuming an API without authentication (like http://rest-service.guides.spring.io/greeting), but receives 401 Forbidden when running it like this. What am I missing? BTW, I'm brand new to API's.
You must have a key and secret, or username and password. Both of them are very necessary to fetch access_token.
i suggest use google postman tool it makes life lot easier in case of api's.
Below code will solve your problem.
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("key:Secret"));
req.Credentials = new NetworkCredential("username", "password");
var postData = "grant_type=client_credentials";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = byteArray.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = req.GetResponse();
// Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(responseFromServer);
String status = (string)o.SelectToken(".access_token");

Categories

Resources