我们如何使用.net代码执行jQuery $ .ajax POST

时间:2015-04-28 06:42:52

标签: jquery .net post webclient

如何在.net?

中使用webclient(或等效的)运行以下代码
function timeout_trigger() {
                $.ajax({
                    type: "POST",
                    url: "Timer.asmx/FetchTimerInfo",
                    data: "{'query':'2342600006524'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                      console.log(msg.d);
                    }
                });
            }

在vb.net中尝试了,我得到了500错误:

    Dim w = New Net.WebClient
    Dim d = New NameValueCollection

    d.Add("query", "2342600006524")

    Dim r = w.UploadValues("http://usage.swiftng.com/Timer.asmx/FetchTimerInfo", d)

我可以使用fiddler composer获得预期的结果:

POST http://usage.swiftng.com/Timer.asmx/FetchTimerInfo HTTP/1.1
Host: usage.swiftng.com
Connection: keep-alive
Content-Length: 25
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/javascript, */*
Origin: http://usage.swiftng.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2376.0 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://usage.swiftng.com/Timer.aspx?2342600006524
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6

{'query':'2342600006524'}

请告知,我哪里错了? 谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用WebRequest类发布数据。请查看此指南Send POST values and get response using HttpWebRequest

这是一个有效的例子:

Dim jsonDataBytes = Encoding.UTF8.GetBytes("{'query':'2342600006524'}")
        Dim req As WebRequest = WebRequest.Create("http://usage.swiftng.com/Timer.asmx/FetchTimerInfo")
        req.ContentType = "application/json"
        req.Method = "POST"
        req.ContentLength = jsonDataBytes.Length


        Dim stream = req.GetRequestStream()
        stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
        stream.Close()

        Dim response = req.GetResponse().GetResponseStream()

        Dim reader As New StreamReader(response)
        Dim res = reader.ReadToEnd()
        reader.Close()
        response.Close()

答案 1 :(得分:0)

我已经解决了这个问题:

    Dim w = New Net.WebClient
    w.Headers("User-Agent") = ("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2376.0 Safari/537.36")
    w.Headers("Content-Type") = ("application/json; charset=UTF-8")

    Dim r = w.UploadData("http://usage.swiftng.com/Timer.asmx/FetchTimerInfo", "POST", Encoding.UTF8.GetBytes("{'query': '2342600006524'}"))
    Dim d = Encoding.UTF8.GetString(r)