2012-01-26 94 views
1

我正在編寫一個API,並希望人們能夠提供Google Charts API調用作爲參數。解析這個有問題的API調用的正確方法是什麼?參數中包含完全獨立的API調用?在C#中,我如何構建和解析嵌套querystrings?

例如:

?method=createimage&chart1=https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World 

在上面的例子中,我想認爲它作爲(2)的查詢字符串的鍵:方法chart1。我能否將上述示例解析爲2個查詢字符串鍵,而不是將Google Charts API調用保持原樣,而不是將其分解?我可以把這個調用作爲JSON還是沿着這些線?

非常感謝!乾杯

回答

6

這裏的正確方法(使用ParseQueryString法):

using System; 
using System.Web; 

class Program 
{ 
    static void Main() 
    { 
     var query = "?method=createimage&chart1=https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World"; 
     var values = HttpUtility.ParseQueryString(query); 
     Console.WriteLine(values["method"]); 
     Console.WriteLine(values["chart1"]); 
    } 
} 

,如果你想建立這樣的查詢字符串:

using System; 
using System.Web; 

class Program 
{ 
    static void Main() 
    { 
     var values = HttpUtility.ParseQueryString(string.Empty); 
     values["method"] = "createimage"; 
     values["chart1"] = "https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World"; 
     Console.WriteLine(values); 
     // prints "method=createimage&chart1=https%3a%2f%2fchart.googleapis.com%2fchart%3fchs%3d250x100%26chd%3dt%3a60%2c40%26cht%3dp3%26chl%3dHello%7cWorld" 
    } 
} 

哦,對了,你給什麼在你的問題是一個無效的查詢字符串,這是由我已經顯示的第二個代碼片段的輸出確認。您應該對您的chart1參數進行URL編碼。在查詢字符串中有多個?字符完全違反所有標準。

這裏是正確的查詢字符串會是什麼樣子:

?method=createimage&chart1=https%3A%2F%2Fchart.googleapis.com%2Fchart%3Fchs%3D250x100%26chd%3Dt%3A60%2C40%26cht%3Dp3%26chl%3DHello%7CWorld 
+0

哈!謝謝。我認爲這會比這更困難。我應該先嚐試一下。非常感謝你的幫助!非常感謝。 – 2012-01-26 22:56:39

0

你應該在你的查詢字符串URL編碼的URL,因爲它包含reserved characters。或者,十六進制編碼也可以很好地工作。

一旦你這樣做了,你可以分別對待這兩個值,解析很簡單。