2017-08-31 64 views
7

我有這樣的代碼創建一個請求,並讀取數據,但它始終是空讀取數據返回空值

 static string uri = "http://yiimp.ccminer.org/api/wallet?address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd"; 

    static void Main(string[] args) 
    { 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
     request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; 

     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

     // Get the stream associated with the response. 
     Stream receiveStream = response.GetResponseStream(); 

     // Pipes the stream to a higher level stream reader with the required encoding format. 
     StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); 

     Console.WriteLine("Response stream received."); 
     Console.WriteLine(readStream.ReadToEnd()); 
     response.Close(); 
     readStream.Close(); 

    } 

當我嘗試訪問從瀏覽器的鏈接我得到這個JSON:

{"currency": "DCR", "unsold": 0.030825917365192, "balance": 0.02007306, "unpaid": 0.05089898, "paid24h": 0.05796425, "total": 0.10886323} 

我錯過了什麼?

+0

你是否收到任何錯誤?請求的狀態碼是什麼? – Jerodev

+0

沒有錯誤,只是一個空值 –

回答

7

當您從瀏覽器執行請求時,會有很多標題發送到Web服務。顯然這個Web服務驗證UserAgent。這是Web服務實現的決定,他們可能不希望您以編程方式訪問它。

var client = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://yiimp.ccminer.org/api/wallet?address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd")); 
client.AutomaticDecompression = DecompressionMethods.GZip; 
client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063"; 
client.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate"; 
client.Host = "yiimp.ccminer.org"; 
client.KeepAlive = true; 

using (var s = client.GetResponse().GetResponseStream()) 
using (var sw = new StreamReader(s)) 
{ 

    var ss = sw.ReadToEnd(); 
    Console.WriteLine(ss); 
} 

發送頭似乎使它的工作。

+0

這似乎工作,錯過標題是問題,謝謝! –