2012-03-31 107 views
1

嗨,大家好,我有一個python腳本,它將一些數據發佈到google並獲取響應。腳本低於Python到紅寶石轉換

net, cid, lac = 24005, 40242, 62211 
import urllib 
a = '000E00000000000000000000000000001B0000000000000000000000030000' 
b = hex(cid)[2:].zfill(8) + hex(lac)[2:].zfill(8) 
c = hex(divmod(net,100)[1])[2:].zfill(8) + hex(divmod(net,100)[0])[2:].zfill(8) 
string = (a + b + c + 'FFFFFFFF00000000').decode('hex') 
try: 
    data = urllib.urlopen('http://www.google.com/glm/mmap',string) 
    r = data.read().encode('hex') 
    print r 
except: 
    print 'connect error' 

我想用ruby腳本得到相同的響應。我無法正確地形成請求,我總是得到badimplementation錯誤或http 501錯誤。你能告訴我錯誤在哪裏嗎? (紅寶石腳本附在下面)。

require 'net/http' 
def fact(mnc,mcc,cid,lac) 
    a = '000E00000000000000000000000000001B0000000000000000000000030000' 
    b = cid.to_s(16).rjust(8,'0') + lac.to_s(16).rjust(8,'0') 
    c = mnc.to_s(16).rjust(8,'0') + mcc.to_s(16).rjust(8,'0') 
    string = [a + b + c + 'FFFFFFFF00000000'].pack('H*') 
    url = URI.parse('http://www.google.com/glm/mmap') 
    resp = Net::HTTP.post_form(url,string) 
    print resp 
end 
puts fact(5,240,40242,62211) 

回答

1

From the documentation

帖子HTML表單數據到指定的URI對象。表單數據必須作爲從字符串到字符串的散列映射提供。

你要傳遞的參數,如果我理解的正確,在表單上: {"param1" => "value1", "param2"=>"value2"}

我只是不明白什麼是你傳遞你的請求參數的名稱。

下面是該方法的Net :: HTTP :: post_form一些使用的實例,也從官方DOC:

實施例1:

uri = URI('http://www.example.com/search.cgi') 
res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50') 
puts res.body 

練習2:

uri = URI('http://www.example.com/search.cgi') 
res = Net::HTTP.post_form(uri, 'q' => ['ruby', 'perl'], 'max' => '50') 
puts res.body 

Link to the examples

希望它有幫助

編輯:接受字符串作爲參數傳遞給POST請求功能:Net::HTTP::request_post

+0

#<的Net :: HTTPNotImplemented:0x107ffa0e8>無我總是得到這個錯誤。 – 2012-03-31 21:45:57

+0

另外,我不應該根據google api發佈爲關鍵值對。我應該像在Python腳本中看到的那樣發佈HEX字符串 – 2012-03-31 21:48:05

+0

因此,您不能使用post_form,而是使用Net :: HTTP.request_post。它將一個字符串作爲參數。試一試,如果服務器仍然以501響應,請參閱實際請求,並將其與python腳本生成的請求進行比較。 – Castilho 2012-03-31 21:49:58