2016-08-11 76 views
1

我試圖使用Microsoft認知驗證API的Python 2.7:https://dev.projectoxford.ai/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523aPython的 - 微軟認知驗證API(PARAMS)

的代碼是:

import httplib, urllib, base64 

headers = { 
    # Request headers 
    'Content-Type': 'application/json', 
    'Ocp-Apim-Subscription-Key': 'my key', 
} 

params = '{\'faceId1\': \'URL.jpg\',\'faceId2\': \'URL.jpg.jpg\'}' 

try: 
    conn = httplib.HTTPSConnection('api.projectoxford.ai') 
    conn.request("POST", "/face/v1.0/verify?%s" % params, "{body}", headers) 
    response = conn.getresponse() 
    data = response.read() 
    print(data) 
    conn.close() 
except Exception as e: 
    print("[Errno {0}] {1}".format(e.errno, e.strerror)) 

我試圖讓conn.request線是這樣的:

conn.request("POST", "/face/v1.0/verify?%s" % params, "", headers) 

錯誤是:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> 
<HTML><HEAD><TITLE>Bad Request</TITLE> 
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD> 
<BODY><h2>Bad Request</h2> 
<hr><p>HTTP Error 400. The request is badly formed.</p> 
</BODY></HTML> 

我alrealy試着跟上,使工作如下代碼:

  1. https://github.com/Microsoft/Cognitive-Emotion-Python/blob/master/Jupyter%20Notebook/Emotion%20Analysis%20Example.ipynb

  2. Using Project Oxford's Emotion API

但是我不能讓這一個工作。我猜這些參數或身體參數有問題。 任何幫助非常感謝。

+0

我認爲JSON格式使用雙引號不單。我會嘗試在paramas中改變它們。 – Dawid

回答

0

的Dawid的評論看起來像它應該修復它(雙引號),嘗試一下本作的Python 2.7:

import requests 

url = "https://api.projectoxford.ai/face/v1.0/verify" 

payload = "{\n \"faceId1\":\"A Face ID\",\n \"faceId2\":\"A Face ID\"\n}" 
headers = { 
    'ocp-apim-subscription-key': "KEY_HERE", 
    'content-type': "application/json" 
    } 

response = requests.request("POST", url, data=payload, headers=headers) 

print(response.text) 

爲Python 3:

import http.client 

conn = http.client.HTTPSConnection("api.projectoxford.ai") 

payload = "{\n\"faceId1\": \"A Face ID\",\n\"faceId2\": \"Another Face ID\"\n}" 

headers = { 
    'ocp-apim-subscription-key': "keyHere", 
    'content-type': "application/json" 
    } 

conn.request("POST", "/face/v1.0/verify", payload, headers) 

res = conn.getresponse() 
data = res.read() 
+0

謝謝@Dawid,@Ryan。恐怕它不起作用。我按照你的說法試過,它顯示錯誤'ImportError:No module named http.client.'如果我更改爲使用'conn = httplib.HTTPSConnection('api.projectoxford.ai')'帶雙引號'payload = 「{\ n \」faceId1 \「:\」A Face ID \「,\ n \」faceId2 \「:\」另一張臉ID「\ n}」我得到這個錯誤:'{「error」 「code」:「BadArgument」,「message」:「Face ID is invalid。」}}' –

+0

對不起,我沒有注意到你使用的是python 2.7。 http.client是python 3的一部分。 –

+0

同樣爲了完整性,您將必須交換實際有效的人臉ID guid(s),例如從上一個/檢測/調用 –

1

你可以參考this question

顯然你並不瞭解代碼。 "{body}"意味着你應該用你的身體,其中包含您請求的URL,就像網站說替換: enter image description here

所以你可以使用這個API是這樣的:

body = { 
      "url": "http://example.com/1.jpg"       
     } 
………… 

conn = httplib.HTTPSConnection('api.projectoxford.ai') 
conn.request("POST", "/face/v1.0/detect?%s" % params, str(body), headers)