从C#客户端调用rest API [英] Call rest API from C# client

查看:478
本文介绍了从C#客户端调用rest API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rest API,返回JSON响应。

我必须从网络应用程序调用这个休息API。



它很容易开发

但是,我想要最简单的方法来调用这个休息网址。





网址:

结算/ customerDetails / {Cid} / billarrangement / {aId} / bill / {bId} / getbillSummary 





方法:获取



示例网址:

 billing / customerDetails / 52145879 / billarrangement / 1234569 / bill / 9879 / getbillSummary?uan = 5214789635 

< br $> b $ b

我尝试过:



 string reqUrl = string.Format(billing / customerDetails / {0} / billarrangement / {1} / bill / {2} getbillSummary?uan = {3},cID,aNo,bId,UAN); 

HttpWebRequest req =(HttpWebRequest)WebRequest.Create(url);
req.Method =GET;
req.Credentials = CredentialCache.DefaultCredentials;
req.Accept =text / json;

使用(HttpWebResponse resp =(HttpWebResponse)req.GetResponse())
{
if(resp.StatusCode == HttpStatusCode.OK)
{
//我的代码
}
}





我想知道这个是否最简单。

或者如果有什么不对,请指正。

如果不是最简单,请帮助我。

解决方案

如果你想保留它,你的代码没有任何问题。你可以看一些第三方库可能会让事情变得更简单。



RestSharp - 用于.NET的简单REST和HTTP客户端 [ ^ ]

I have a rest API, returns JSON response.
I have to call this rest API from web application.

it's quite easy to develop
But, I want the simplest way to call this rest url.


Url :

billing/customerDetails/{Cid}/billarrangement/{aId}/bill/{bId}/getbillSummary



Method: GET

example URL :

billing/customerDetails/52145879/billarrangement/1234569/bill/9879/getbillSummary?uan=5214789635



What I have tried:

string reqUrl = string.Format("billing/customerDetails/{0}/billarrangement/{1}/bill/{2}getbillSummary?uan={3}", cID, aNo, bId, UAN);

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.Credentials = CredentialCache.DefaultCredentials;
req.Accept = "text/json";

using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
      if (resp.StatusCode == HttpStatusCode.OK)
      {
        // my code
      }
}



I want to know if this one is simplest.
Or if anything wrong, please correct me.
If its not simplest, please help me with that.

解决方案

There's nothing wrong with your code if you want to keep it. There are some third-party libraries you could look at that might make things a little simpler.

RestSharp - Simple REST and HTTP Client for .NET[^]


这篇关于从C#客户端调用rest API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆