2012-05-09 204 views
0

我想使用python進行地址驗證使用CDYNE服務。請求CDYNE結果在urllib2.HTTPError:HTTP錯誤400:錯誤的請求

我用this作爲參考來創建POST要求,它看起來像下面

import urllib2 
import urllib 

url = 'http://pav3.cdyne.com/PavService.svc/VerifyAddressAdvanced' 
data = {} 

data['CityName'] = 'San Francisco' 
data['FirmOrRecipient'] = 'CDYNE' 
data['LicenseKey'] = 'valid_key' 
data['PrimaryAddressLine'] = '45 fremont street' 
data['ReturnCaseSensitive'] = True 
data['ReturnCensusInfo'] = True 
data['ReturnCityAbbreviation'] = True 
data['ReturnGeoLocation'] = True 
data['ReturnLegislativeInfo'] = True 
data['ReturnMailingIndustryInfo'] = True 
data['ReturnResidentialIndicator'] = True 
data['ReturnStreetAbbreviated'] = True 
data['SecondaryAddressLine'] = '' 
data['State'] = 'CA' 
data['Urbanization'] = '' 
data['ZipCode'] = '94105' 

,併發布要求如下

data_encoded = urllib.urlencode(data) 
req = urllib2.Request(url, data_encoded) 
response = urllib2.urlopen(req) 

我看到錯誤的

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen 
    return _opener.open(url, data, timeout) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 398, in open 
    response = meth(req, response) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 511, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 436, in error 
    return self._call_chain(*args) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 370, in _call_chain 
    result = func(*args) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 519, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 400: Bad Request 

我這是新的,所以不明白已經發生了什麼請幫助

回答

1

您必須將請求發送爲jsonxml格式的文檔,該架構位於您已鏈接到的頁面上。
你正在發送一個urlencoded請求,這是api不支持的。

編輯:這就是它會是什麼樣子使用JSON

import json 
data_encoded = json.dumps(data) 
req = urllib2.Request(url, data_encoded, {'Content-Type': 'application/json'}) 
response = urllib2.urlopen(req) 
print response.read() 
# ... 
+0

馬塔,我該怎麼做呢?我沒有看到這樣做的方式 – daydreamer

+0

這工作就像一個魅力!謝謝你Mata – daydreamer