使用C#.net在winform中调用和使用Web API

时间:2015-09-22 11:53:27

标签: c# .net json winforms asp.net-web-api

我是初学者并创建winform应用程序。其中我必须使用API​​进行简单的CRUD操作。我的客户与我共享了API,并要求以JSON的形式发送数据。

API:http://blabla.com/blabla/api/login-valida

KEY:“HelloWorld”

价值:{“email”:“user@gmail.com”,“密码”:“123456”,“时间”:“2015-09-22 10:15:20”}

回复:Login_id

如何将数据转换为JSON,使用POST方法调用API并获得响应?

修改 在stackoverflow的某个地方,我找到了这个解决方案

public static void POST(string url, string jsonContent)
    {
        url="blabla.com/api/blala" + url;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL);
        request.Method = "POST";

        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        Byte[] byteArray = encoding.GetBytes(jsonContent);

        request.ContentLength = byteArray.Length;
        request.ContentType = @"application/json";

        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }
        long length = 0;
        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                length = response.ContentLength;

            }
        }
        catch
        {
            throw;
        }
    }
//on my login button click 
    private void btnLogin_Click(object sender, EventArgs e)
    {
        CallAPI.POST("login-validate", "{ \"email\":" + txtUserName.Text + " ,\"password\":" + txtPassword.Text + ",\"time\": " + DateTime.Now.ToString("yyyy-MM-dd h:mm tt") + "}");
    }

我得到异常,说“远程服务器返回错误:(404)Not Found。”

4 个答案:

答案 0 :(得分:10)

你可以看看

您需要的第一件事是安装Web API客户端库:
从Tools菜单中,选择Library Package Manager,然后选择Package Manager Console。在“程序包管理器控制台”窗口中,键入以下命令:

Install-Package Microsoft.AspNet.WebApi.Client

然后发送这样的帖子请求

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}

答案 1 :(得分:4)

答案 2 :(得分:2)

只需使用以下库即可。

https://www.nuget.org/packages/RestSharp

GitHub项目:https://github.com/restsharp/RestSharp

示例代码::

    public Customer GetCustomerDetailsByCustomerId(int id)
    {
        var client = new RestClient("http://localhost:3000/Api/GetCustomerDetailsByCustomerId/" + id);
        var request = new RestRequest(Method.GET);
        request.AddHeader("X-Token-Key", "dsds-sdsdsds-swrwerfd-dfdfd");
        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string
        dynamic json = JsonConvert.DeserializeObject(content);
        JObject customerObjJson = jsonData.CustomerObj;
        var customerObj = customerObjJson.ToObject<Customer>();
        return customerObj;
    }

答案 3 :(得分:0)

使用此代码:

http ={" xxx": "#phone#","yyy": "1234", "zzz":5678 }

input= {"phone": "2", "id": "258 },