如何在Windows窗体应用程序上使用$ .getJSON

时间:2015-09-18 14:12:37

标签: c# jquery httpwebrequest

下面的代码正在运行,但我希望在我的Windows窗体应用程序中使用httpwebrequest来获取数据。

$.getJSON("JSONHandler", {
     metod: "mymethod",
     param: {
         id: "123",
         name: "Jhon",
         surname: "Tiger",
         birthdate: "7.2.1949"
     }
 }, function (json) {
     if (json.Mesaj)
         return alert(json.Mesaj);
     if (json.hasinfo) {            
        PageMethods.MyMethod(JSON.stringify(json.phoneNo));
     }
     else {
         alert("Something wrong");
     }
});

我尝试在下面编码

var httpWebRequest = (HttpWebRequest)WebRequest.Create("JSONHandler");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = "{" +
     " \"metod\": \"mymethod\", " +
     " \"param\": { " +
         " \"id\": \"123\", " +
         " \"name\": \"Jhon\", " +
        "  \"surname\": \"Tiger\", " +
         " \"birth\": \"7.2.1949\" " +
     " } " +
 " }";

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var responseText = streamReader.ReadToEnd();
    //Now you have your response.
    //or false depending on information in the response

}

但它从服务器返回nullpointer异常错误我的params是错误的。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我认为您可以使用httpClient

从Windows窗体应用程序执行此操作

以下是示例代码,它将一堆产品发送到REST服务。

更新:此代码应与您示例中的数据一起使用。

var person = new {
         id= "123",
         name= "Jhon",
         surname= "Tiger",
         birthdate= "7.2.1949"
     }
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("JSONHandler");
    var result = client.PostAsJsonAsync("/mymethod", person).Result;
    switch (result.StatusCode)
    {
        case HttpStatusCode.OK:
            Trace.TraceInformation("Updated ok");
            break;
        default:
            Trace.TraceError("Something went wrong");
            break;
    }
}