2013-08-20 86 views
3

我需要做一個POST請求如:如何在客戶端進行自定義的「POST」請求?

POST /feeds/api/users/default/subscriptions HTTP/1.1 
Host: gdata.youtube.com 
Content-Type: application/atom+xml 
Content-Length: CONTENT_LENGTH 
Authorization: Bearer ACCESS_TOKEN 
GData-Version: 2 
X-GData-Key: key=DEVELOPER_KEY 

<?xml version="1.0" encoding="UTF-8"?> 
<entry xmlns="http://www.w3.org/2005/Atom" 
    xmlns:yt="http://gdata.youtube.com/schemas/2007"> 
    <category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat" 
     term="channel"/> 
    <yt:username>GoogleDevelopers</yt:username> 
</entry> 

我知道如何做到這一點的服務器(.NET/C#)側例如使用HttpWebRequest對象,設置頁眉/方法/ ContentType的。

但是,如果我想要做客戶端? Ajax與jQuery?我可以在哪裏設置這些參數?

回答

2

您可以使用此功能:使用這樣的代碼

function post(url, data, headers, success) { 
    $.ajax({ 
     beforeSend: function(xhr){ 
      $.each(headers, function(key, val) { 
       xhr.setRequestHeader(key, val); 
      }); 
      xhr.setRequestHeader('Content-Length', data.length); 
     } 
     type: "POST", 
     url: url, 
     processData: false, 
     data: data, 
     dataType: "xml", 
     success: success 
    }); 
} 

var request = '<?xml version="1.0" encoding="UTF-8"?>' + 
     '<entry xmlns="http://www.w3.org/2005/Atom"' + 
     '  xmlns:yt="http://gdata.youtube.com/schemas/2007">' + 
     ' <category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat" term="channel"/>'+ 
     ' <yt:username>GoogleDevelopers</yt:username>' + 
     '</entry>'; 

var headers = { 
    'Content-Type': 'application/atom+xml', 
    'Authorization': 'Bearer ACCESS_TOKEN' 
    'GData-Version': 2 
    'X-GData-Key': 'key=DEVELOPER_KEY' 
}; 

post('/some/url', request, headers, function(response) { 
    alert(response); 
}); 
+0

似乎可以完美運行,即使YouTube的401錯誤答覆!但錯誤在別處!謝謝... – markzzz

相關問題