2012-07-07 116 views
1

我在嘗試對運行在Glassfish上的web服務進行Python REST POST時遇到困難。我已經證實,使用CURL,POST可以正常工作,但對Python沒有好運。向Glassfish服務器發送Python請求的RESTFUL POST

這是可以正常工作的CURL請求。

curl -X POST -H "Content-Type: application/json" -d '{"id":1,"lastname":"smith"}' 
    http://192.168.0.20:8080/field1/resources/com.field1entity.field1 

這裏是Python代碼,以使POST請求從控制檯

import urllib 
import httplib2 

def call(): 
http = httplib2.Http() 

url = 'http://192.168.0.20:8080/field1/resources/com.field1entity.field1' 

params = urllib.urlencode({"id":11111,"lastname":"oojamalip"}) 

response, content = http.request(url, 'POST', params, headers={'Content-type':'application/json'}) 
print "lets stop here to have a looksy at the variables"        
print content 

if __name__ == '__main__': 

namesPage = call() 
print namesPage 

輸出,

意外字符( 'L'(代碼108)) :期望一個有效的值(數字,字符串,數組,對象,'true','false'或'null') at [Source:org.ap [email protected];行:1,柱:2]

希望有人能闡明該問題的一些光。

感謝 尼克

回答

2

您是URL編碼的嬰兒車,然後告訴它是JSON編碼

import json 

params = json.dumps({"id":11111,"lastname":"oojamalip"}) 
# then 
response, content = http.request(url, 'POST', body=params, headers={'Content-type':'application/json'}) 
+0

菲爾喜服務器,這完美地工作。 – 2012-07-08 12:59:20

+0

@om_kcin非常歡迎SO。記得「接受」有效的答案,以獲得更好的答覆率 – 2012-07-08 15:08:49

+0

嗨菲爾,接受的答案(我認爲)再次感謝您的幫助 – 2012-07-14 14:38:33