TechDo
TechDo

Reputation: 18629

Connecting to PHP api from c# project

I have an api

http://cbastest.cadvilpos.com/module/posmodule/customapi

with parameters

{
    "action":4,
    "device_token": "3e8ea119a90ee6d2",
    "key":"9475962085b3a1b8c475d52.95782804",
    "shop":1,
    "language":1
  }

This is working fine in postman. But when I try to connect from c# project its showing an error {"success":0,"error":"Missing the action parameter."}. Please give a working C# code to get the json result.

The code I tried:

var request = (HttpWebRequest)WebRequest.Create("http://cbastest.cadvilpos.com/module/posmodule/customapi");
var postData = "{ 'action':'4', 'device_token':'3e8ea119a90ee6d2','key':'9475962085b3a1b8c475d52.95782804','shop':'1','language':'1'}";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response2 = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response2.GetResponseStream()).ReadToEnd();

Upvotes: 0

Views: 5361

Answers (2)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131334

You don't need to use a raw HttpWebRequest object to make an HTTP call. HttpClient was introduced in 2012 to allow easy asynchronous HTTP calls.

You could do something as simple as :

var content=new StringContent(postData,Encoding.UTF8, "application/json");
HttpResponseMessage response=await httpClient.PostAsync(url,content);
//Now process the response
if (response.IsSuccessCode)
{
   var body=await response.Content.ReadAsStringAsync();
   var responseDTO=JsonConvert.DeserializeObject<MyDTO>(body);
}

Instead of building a JSON string by hand you could use a strongly typed class or an anonymous object and serialize it to JSON with JSON.NET :

var data=new {
    action=4,
    device_token="3e8ea119a90ee6d2",
    key = "9475962085b3a1b8c475d52.95782804",
    shop=1,
    language=1
};

var postData=JsonConvert.SerializeObject(data);
var content=new StringContent(postData,Encoding.UTF8, "application/json");
var response=await httpClient.PostAsync(url,content);
...

You can read a response body in one go as a string, using ReadAsStringAsync or you can get the response stream with ReadAsStreamAsync. You could copy the response data directly to another stream, eg a file or memory stream with HttpContent.CopyToAsync

Check Call a Web API from a .NET Client for more examples. Despite the title, the examples work to call any HTTP/REST API.

The Microsoft.AspNet.WebApi.Client package mentioned in that article is another thing that applies to any call, not just calls to ASP.NET Web API. The extension method PostAsJsonAsync for example, combines serializing and posting a request to a url. Using it, posting the action DTO could be reduced to a single line:

var data=new {
    action=4,
    device_token="3e8ea119a90ee6d2",
    key = "9475962085b3a1b8c475d52.95782804",
    shop=1,
    language=1
};

var response=await httpClient.PostAsJsonAsync(url,data);

Upvotes: 2

Josh
Josh

Reputation: 4438

There is a button in Postman that will generate code for the currently defined request. The link is here: enter image description here

And this is what the code looks like. You'll need to pull in RestSharp from Nuget enter image description here

Upvotes: 1

Related Questions