I'm creating a MetroStyle app and I want to use a website API that is based on the HTTP Get methods. For instance to login I should download the XML returned by this URL:
websitehost.com/api/login.php?u=username&p=password
The problem is that the new MetroStyle apps won't let me to use many of the methods I've been using for years in .Net so how can I download the returned XML document and parse it?
You might be searching for this:
public async Task<string> DownloadPageStringAsync(string url)
{
HttpClientHandler handler = new HttpClientHandler()
{ UseDefaultCredentials = true, AllowAutoRedirect = true };
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
You can use either the Windows.Data.Xml.Dom.XmlDocument.LoadFromUriAsync(Uri) method to automatically acquire and parse the XML, or you could manually use a Windows.Networking.BackgroundTransfer.DownloadOperation instance to call the web service and acquire the data, and Windows.Data.Xml.Dom.XmlDocument.LoadXml(string) to parse the data.
You should be able to use
var data = await (new System.Net.Http.HttpClient()).GetAsync(new Uri("http://wherever"));
And then do whatever you need with the data, including loading it with XmlDocument or XElement or whatnot.
Related
I'm sending data via GRPC to, let's call it, IntegrationApi, calling a method Foo. I need to read header values from the response (the API I'm communicating with sends rate-limiting headers).
I'm using https://www.nuget.org/packages/Grpc.Core/
var metaData = new Metadata();
metadata.Add(new Metadata.Entry("Authorization", $"Bearer {apiKey}"));
var channel = new Channel("url to endpoint", new SslCredentials());
var client = new IntegrationApi(channel);
var callOptions = new CallOptions()
.WithHeaders(metadata)
.WithDeadline(DateTime.UtcNow.AddSeconds(15))
.WithWaitForReady(false);
var response = client.Foo(req, options);
but the response only gives me the properties based on the Foo.proto file.
How do I do this?
You are using the synchronous version of "Foo" method, and that one uses a simplified version of the API (=only allows access to the response and throws RpcExceptions in case of an error).
If you call the asynchronous version of the same method ("FooAsync"), you'll get back a call object that can access all the call details (such as response headers).
https://github.com/grpc/grpc/blob/044a8e29df4c5c2716c7e8250c6b2585e1c425ff/src/csharp/Grpc.Core.Api/AsyncUnaryCall.cs#L73
I am using HttpClient PostAsync to send data to a URI. However, the following code doesn't behave as expected:
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{"cpm_site_id",TOKEN},
{"apikey",API_KEY},
{"cpm_amount",input.Amount},
{"cpm_currency",input.Currency},
{"cpm_trans_id",input.Id},
{"cpm_custom",input.Custom},
};
// Get the parameters in the url encoded format
var content = new FormUrlEncodedContent(values);
//Send request
var response = await client.PostAsync(new Uri(Urls.GetUrl(Methods.Pay, IS_PRODUCTION_SITE)), content);
When the client closes their browser, I want to receive an event notification to call this code, send the above data to the client, and open a new browser instance to perform additional actions. However, this code doesn't accomplish this and I'm not sure exactly why.
I think you'll need to use something like Selenium to automate a web browser. The HttpClient can perform HTTP functions, but does not work like a web browser does.
See this SO post for a 'hello world' example
See this SO post for an example of capturing the browser close event. I've not done this with C#, but I'd imagine it'll be similar to this JAVA example.
As the question says, is it possible? I need my code in server side to call a third-party REST API to get some data.
As mentioned by #ramiramilu you can use HttpClient class to achieve the same.
var client = new HttpClient();
client.BaseAddress = new Uri("http://mybaseaddress/");
HttpResponseMessage response = await client.GetAsync("someEndpoint");
if (response.IsSuccessStatusCode)
{
var model = await response.Content.ReadAsAsync<MyModel>();
}
Hope it helps!
If you are using .net 4.5 , You can do an ASync request.
This is rather similar in concept to what you're asking for.
I'm new to testing and test automation and I'm trying to test a REST API for performance. For this my primary preference is Visual Studio but I'd like to hear about other options too. I want to capture the json response from a REST call, extract some parameters from the JSON response I got and pass them to the next REST call. It's like automatic parameter detection. I did a search online but could only find something like this https://msdn.microsoft.com/library/dn250793.aspx but no where they really talk about testing REST service with Visual Studio. Any pointers will be of great help. Thank you.!
You can easily talk to a JSON REST Web API service from C# code. You'd need the service running then you can write tests which talk to the API service and give you timings or parse the response and call the next API method, etc.
Here's a simple example
public async Task<YourResponseDTO> GetResponseDTO()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("localhost/your-web-api/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("your-first-endpoint");
if (!response.IsSuccessStatusCode)
{
return null;
}
var mediaType = response.Content.Headers.ContentType.MediaType;
if (mediaType != "application/json")
{
return null;
}
var responseObject = await response.Content.ReadAsAsync<YourResponseDTO>();
return responseObject;
}
}
You simply write the class YourResponseDTO to match whatever fields come out of JSON and this code will automatically populate the fields.
Basically my idea is to develop a proxy which will run in windows
I have created windows service application which running successfully and i have integrated a web service code in the windows service application running in windows service.
How to call that web service method when the client hits my url?
How to form the url which can call web service method to get the method return value?
OK, I'll try to answer.
Let's assume you want to call REST web service. What do you need? A HttpClient and (probably) JSON/XML Serializer. You can use built-in .NET classes, or a library like RestSharp
Sample calling REST web service using RestSharp
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", 123); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
You are not required to use RestSharp, no. For simple cases HttpWebRequest (+DataContractJsonSerializaer or Xml analogue) will be just perfect
Having SOAP web service?
Follow the instructions provided here