2012-04-24 147 views
1

我想知道Intersango API(文檔記錄不完整)的正確URL格式。我在C#編程我的客戶,但我看Python example和我有點困惑,什麼是真正被放置在請求主體:如何向Intersango API發送請求

def make_request(self,call_name,params): 
    params.append(('api_key',self.api_key)) // <-- How does this get serialized? 
    body = urllib.urlencode(params) 

    self.connect() 

    try: 
     self.connection.putrequest('POST','/api/authenticated/v'+self.version+'/'+call_name+'.php') 
     self.connection.putheader('Connection','Keep-Alive') 
     self.connection.putheader('Keep-Alive','30') 
     self.connection.putheader('Content-type','application/x-www-form-urlencoded') 
     self.connection.putheader('Content-length',len(body)) 
     self.connection.endheaders() 

     self.connection.send(body) 

     response = self.connection.getresponse() 

     return json.load(response) 
//... 

我想不通出這段代碼:params.append(('api_key',self.api_key))

它是某種字典,它被序列化爲JSON,逗號分隔或者它是如何被序列化的?當參數被編碼並分配給它時,身體會是什麼樣子?

P.S.我沒有任何可以運行代碼的東西,所以我可以調試它,但是我只是希望這足夠簡單,可以理解知道Python的人,並且他們能夠告訴我該線路上發生了什麼的代碼。

+0

你能夠使它發揮作用?我遵循相同的步驟,但根本無法獲得經過身份驗證的API工作,得到{「遠程服務器返回錯誤:(417)期望失敗。」} – galets 2012-06-20 04:01:55

回答

1

params是2元素列表的列表。該列表看起來像((key1, value1), (key2, value2), ...)

params.append(('api_key',self.api_key))又增加了2元列表現有PARAMS列表。

最後,urllib.urlencode藉此列表,並將它轉換成一個PROPERT url編碼字符串,在這種情況下,它會返回一個字符串key1=value1&key2=value2&api_key=23423如果你的密鑰或值中有任何特殊字符,urlencode會對它們進行編碼,參見documentation for urlencode

1

我試圖讓C#代碼工作,並且它保持失敗,異常{「遠程服務器返回一個錯誤:(417)期望失敗。「}我終於發現問題所在,你可以閱讀它在深入here

總之,要使C#訪問Intersango API的方法是添加以下代碼:

此代碼需要只運行一次。這是一個全局設置,因此會影響您的完整應用程序,因此請注意其他事情可能會因此而中斷。

下面是一個示例代碼:

System.Net.ServicePointManager.Expect100Continue = false; 
var address = "https://intersango.com/api/authenticated/v0.1/listAccounts.php"; 
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
var postBytes = Encoding.UTF8.GetBytes("api_key=aa75***************fd65785"); 
request.ContentLength = postBytes.Length; 
var dataStream = request.GetRequestStream(); 
dataStream.Write(postBytes, 0, postBytes.Length); 
dataStream.Close(); 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
1

蛋糕 代替params.append(('api_key',self.api_key)) 的片只寫:

params['api_key']=self.api_key