Making a simple C# API call [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm trying to teach myself how to make simple API calls with C#. I'd like to call this "http://hivemc.com/json/userprofile/da10b68dea6a42d58ea8fea66a57b886". This should return some strings in json but I don't know what i'm supposed to do with that.
reference: https://apidoc.hivemc.com/#!/GameData/get_game_game_data_id_UUID
I'm new to programming and I've never done anything with API's. I've tried looking around the internet but I don't understand what I'm supposed to look for. Can someone refer me to an article that can teach me how to do this? I have no idea where to start. An example of the code with explanation would be great but I understand if it's too much to ask.
Thank you!

You can start from the following.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Test
{
public static void Do()
{
var result = GetGameData("da10b68dea6a42d58ea8fea66a57b886").Result;
//TODO parse json here. For example, see http://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c
Console.WriteLine(result);
}
private static async Task<string> GetGameData(string id)
{
var url = "http://hivemc.com/json/userprofile/" + id;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string strResult = await response.Content.ReadAsStringAsync();
return strResult;
}
else
{
return null;
}
}
}
}
Sample call
Test.Do();

You should use System.Net.HttpClient from Nuget. Check this link out. It shows you how to get data from the API. The next step is to deserialize it to your model using Newtonsoft.Json.
Hope it helps!

Related

How to interact with a REST service in C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm developing a small application that has to interact with a JSON/REST service.
What is the easiest option to interact with it in my c# application.
I don't need to have the best performances, since it's just a tools that will do some synchronization once a day, I'm more oriented toward the ease of use and the time of development.
(the service in question will be our local JIRA instance).
I think the best way by far is to use RestSharp. It's a free Nuget Package that you can reference. It's very easy to use and this is the example from their website:
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
IRestResponse 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();

Call a remote WEB API [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Good evening,
I am new in c# and asp.net
I have created an MVC 4 WEB Application and I am using aspx as the view.
I am trying to call a remote web API and unfortunately I do not get it, in order to display the data on my web site.
I created one controller and inside the controller in the Index() method I wrote this code:
public class CallAPIController : Controller
{
//
// GET: /CallAPI/
public async Task<string> Index()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://remoteWEBAPI/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/data").Result; // Blocking call!
string json = await response.Content.ReadAsStringAsync();
Debug.WriteLine("Content: " + json);
return json;
}
}
I am new to this technologies, I have tried many things and I have been struggling with this for the last 4-5 hours.I do not know how to solve this problem. Could you please help me? I do not think it should be very difficult for someone expert familiar with these...
Assuming your WebAPI accepts GET method and returning a JSON string.
WebClient client = new WebClient();
client.Headers["Accept"] = "application/json";
string returnedString = client.DownloadString(new Uri("http://yourwebapi.com/api/data"));

Sip parser in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I am looking for a library or class in c# that can parse sip packets.
I need functions that will help me get the
Call-ID field from the packet, types of requests, and basically breakdown the sip packet to its fields.
Does anybody know something that can help me?
Thanks, ofek
This class from my sipsorcery project can do it for you.
Update: If you have a string that contains a full SIP packet you can parse the full thing by using:
var req = SIPSorcery.SIP.SIPRequest.ParseSIPRequest(reqStr);
var headers = req.Header;
var resp = SIPSorcery.SIP.SIPResponse.ParseSIPResponse(respStr);
var headers = resp.Header;
If you don't know whether the SIP packet is a request or a response you can use the SIPMessage class:
var mess = SIPSorcery.SIP.SIPMessage.ParseSIPMessage(messStr, null, null);
var headers = SIPSorcery.SIP.SIPHeader.ParseSIPHeaders(mess.SIPHeaders);
Update 2:
Given you're using pcap.net to capture the SIP packets you are probably ending up with a block of bytes rather than a string. You can use the SIPMessage class to parse the SIP packet from a UDP payload:
var mess = SIPSorcery.SIP.SIPMessage.ParseSIPMessage(packet.Ethernet.IPv4datagram.Udp.Payload, null, null);
var headers = SIPSorcery.SIP.SIPHeader.ParseSIPHeaders(mess.SIPHeaders);

I cant simply await GetStringAsync? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I thought I could do i straight forward, but maybe there is something wrong with my setup? I'm trying to download a string in my app for logging in:
private async void DoLogin()
{
HttpClient client = new HttpClient();
string response = await client.GetStringAsync(Config.SERVER_URL + "/Login/");
All logic is removed, im going to add headers and so on, but VS2012 will no allow me to await that response.
I tried to follow the code from here, but in my case I only get Cannot await 'System.Threading.Tasks.Task<string'.
Why is that? Should'nt GetStringAsync simply return me a string? It returns a Task<string>, but do I have to wrap it in a method?
Your code is perfectly fine. However: In order to use async / await in portable class libaries you need to add the NuGet package Microsoft.Bcl.Async to your project.
Also please note the comment of Servy to use the return type Task instead of void.

How can i check website content plagiarism by posting a particular Url in my Asp.net MVC Project? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I need to implement a method for checking plagiarism in website content.
When I submit a particular URL I need to get the places where the web content is used or manipulated.
Is there any API to do that?
I'm using Copyleaks API to check for plagiarism, it fully supports C# and .Net applications. The API is based on HTTP RESTful architecture. It's pretty simple to integrate and work with.
Create a new visual studio project and install Copyleaks API Nuget Package.
To scan your content for plagiarism simply call the function 'scan' with your credentials. Here is a sample code (from their open source GitHub SDK):
public void Scan(string username, string apiKey, string url)
{
// Login to Copyleaks server.
Console.Write("User login... ");
LoginToken token = UsersAuthentication.Login(username, apiKey);
Console.WriteLine("\t\t\tSuccess!");
// Create a new process on server.
Console.Write("Submiting new request... ");
Detector detector = new Detector(token);
ScannerProcess process = detector.CreateProcess(url);
Console.WriteLine("\tSuccess!");
// Waiting to process to be finished.
Console.Write("Waiting for completion... ");
while (!process.IsCompleted())
Thread.Sleep(1000);
Console.WriteLine("\tSuccess!");
// Getting results.
Console.Write("Getting results... ");
var results = process.GetResults();
if (results.Length == 0)
{
Console.WriteLine("\tNo results.");
}
else
{
for (int i = 0; i < results.Length; ++i)
{
Console.WriteLine();
Console.WriteLine("Result {0}:", i + 1);
Console.WriteLine("Domain: {0}", results[i].Domain);
Console.WriteLine("Url: {0}", results[i].URL);
Console.WriteLine("Precents: {0}", results[i].Precents);
Console.WriteLine("CopiedWords: {0}", results[i].NumberOfCopiedWords);
}
}
}
For more information, read their full tutorial.
I am afraid that such method doesn't exist.

Categories