2011-02-10 148 views
1

我想從Firefox擴展發送POST請求到Web服務器。從Firefox擴展發送POST請求

我發現這個例子發送POST請求; https://developer.mozilla.org/en/Creating_Sandboxed_HTTP_Connections#HTTP_notifications

但我不能得到它的工作。

我目前有這樣的代碼;

var ioService = Components.classes["@mozilla.org/network/io-service;1"] 
           .getService(Components.interfaces.nsIIOService); 
var uri = ioService.newURI("http://www.google.com", null, null); 
gChannel = ioService.newChannelFromURI(uri); 

postData = "a=1&b=2&c=3"; 

var inputStream = Components.classes["@mozilla.org/io/string-input-stream;1"] 
    .createInstance(Components.interfaces.nsIStringInputStream); 

inputStream.setData(postData, postData.length); 

var uploadChannel = gChannel.QueryInterface(Components.interfaces.nsIUploadChannel); 

uploadChannel.setUploadStream(inputStream, "application/x-www-form-urlencoded", -1); 
uploadChannel.requestMethod = "POST"; 
uploadChannel.open(); 

,但我得到一個錯誤「不能修改WrappedNative的性質」

回答

4

關於使用XMLHttpRequest對象如何。 擴展開發中沒有相同的來源策略

+0

我的代碼,我使用Components.utils.import導入一個模塊中,它似乎並沒有能夠訪問和創建新的XMLHttpRequest對象。 – 2011-02-10 09:22:48

+2

@ user329931`Components.classes [「@ mozilla.org/xmlextras/xmlhttprequest; 1」]。createInstance();` – Neil 2011-02-10 20:20:25

1

requestMethod是nsIHttpChannel上的一個屬性,所以您需要先調用gChannel上的QueryInterface,然後才能對其進行設置。

3

我使用下面的代碼來測試一個URL存在:

if(typeof XMLHttpRequest == "undefined"){ 
     var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] 
          .createInstance(); 
} 
else{ 
     var req = new XMLHttpRequest(); 
} 
try{ 
    req.open("GET", "https://" + request.URI.host + request.URI.path); 
    var timeOutID = httpNowhere._getWindow().setTimeout(function() { 
     req.abort(); 
     Services.prompt.alert(null,"Info","nok "+ "https://" + request.URI.host 
               + request.URI.path); 
    }, (redirectTimer)); 

    req.onreadystatechange = function (e) { 

      if (req.readyState==4){ 
       Services.prompt.alert(null,"Info","ok "+ "https://" + request.URI.host 
                 + request.URI.path); 
       req.abort(); 
      } 
     } 
    req.send(null); 

} catch (err) { 
Services.prompt.alert(null,"Info",err); 
}