使用C#.net调用和使用Winform中的Web API [英] Call and consume Web API in winform using C#.net

查看:248
本文介绍了使用C#.net调用和使用Winform中的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am beginner and creating winform application. In which i have to use API for Simple CRUD operation. My client had shared API with me and asked to send data in form of JSON.

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

KEY:"HelloWorld"

KEY : "HelloWorld"

值:{电子邮件":"user@gmail.com",密码":"123456",时间":"2015-09-22 10:15:20"}

Value : { "email": "user@gmail.com","password": "123456","time": "2015-09-22 10:15:20"}

响应:Login_id

Response : Login_id

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

How can i convert data to JSON, call API using POST method and get response?

编辑 我在stackoverflow的某个地方找到了这个解决方案

EDIT Somewhere on stackoverflow i found this solution

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)未找到."

I got exception that says "The remote server returned an error: (404) Not Found."

推荐答案

您可以查看以下文档教程:

You can take a look at the following docs tutorial:

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