2015-04-28 17 views
0

如何在.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) 

我能夠使用小提琴手作曲家得到預期的結果:

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'} 

請指教,其中我錯了嗎? 謝謝!

回答

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() 
+0

不大,您提供的網址沒有說太多 –

+0

你有沒有嘗試在這個問題上的VB代碼? – Oluwafemi

+0

我已經完成了它,指定content-Type並使用UploadData。 –

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)