2017-02-18 146 views
0

我目前張貼到一個服務器,像這樣的JSON響應:充分利用POST請求的Python

req = urllib2.Request('http://xxx.xxx.xx.xx/upload/') 
req.add_header('Content-Type', 'application/json') 
response = urllib2.urlopen(req, json_string) 
print(response.getcode()) 

我得到一個200碼回不過我想讀服務器發回的JSON。我該怎麼做呢? (搭售以避免使用請求庫)

+0

從[文件](HTTPS: //docs.python.org/2/library/urllib2.html#urllib2.urlopen):getcode() - 返回響應的HTTP狀態碼。 –

回答

0

我沒有得到代碼,因爲我沒有url。 嘗試:

req = urllib2.Request('http://xxx.xxx.xx.xx/upload/') 
req.add_header('Content-Type', 'application/json') 
response = urllib2.urlopen(req, json_string) 
print(response.read()) 
0

爲了得到響應不只是你需要分析與json

import json 
req = urllib2.Request('http://xxx.xxx.xx.xx/upload/') 
req.add_header('Content-Type', 'application/json') 
response = urllib2.urlopen(req, json_string) 
json_response = json.loads(response.read().decode('ascii')) 

的響應json序列化的字符串的實際json對象的編碼也可能是utf-8取決於服務器發回你的喲。

另外,您可以使用requests庫,我覺得更容易互動,你需要單獨安裝它雖然與pip install requests

import requests, json 
response = requests.post('http://xxx.xxx.xx.xx/upload', data={'data': json_string}) 
if response.ok: 
    response_json = response.json() 
else: 
    print('Something went wrong, server sent code {}'.format(response.status_code)) 

requests library docs