【发布时间】:2015-12-19 09:21:35
【问题描述】:
我是初学者,正在创建 winform 应用程序。在其中我必须使用 API 进行简单的 CRUD 操作。我的客户与我共享 API 并要求以 JSON 的形式发送数据。
API:http://blabla.com/blabla/api/login-valida
键:“HelloWorld”
值:{“电子邮件”:“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) 未找到。”
【问题讨论】:
标签: c# asp.net .net winforms asp.net-web-api