[Azure Congnitive QnA rest] Python 使用 HTTPSConnection 调 API 遇到 <class ‘socket.gaierror‘> 错误, 中文乱码

Github sample地址:https://github.com/Azure-Samples/cognitive-services-qnamaker-python/blob/master/documentation-samples/quickstarts/get-answer/get-answer-3x.py

VS Code,anaconda的Python3.7,运行sample遇到错误:

Unexpected error: <class 'socket.gaierror'>
Unexpected error: [Errno 8] nodename nor servname provided, or not known

百度下,很多说host文件等等,仔细查看下,错误其实很简单,是Host地址前面不能带有 "https://"

  # Represents the various elements used to create HTTP request URIs
  # for QnA Maker operations.
  # From Publish Page
  # Example: YOUR-RESOURCE-NAME.azurewebsites.net
  # CAUTION: This is not the exact value of HOST field
  # HOST trimmed to work with http library
  host = "YOUR-RESOURCE-NAME.azurewebsites.net";

这个sample,直接输入文中问题,后台服务会不识别:

发送前:encodedQuestion = question.encode("utf-8")

拿到结果后解析:print(json.dumps(json.loads(answer, encoding="utf-8"), ensure_ascii=False, indent=4))

代码:

# -*- coding:utf-8 -*-

import http.client, urllib.parse, json, time, sys

# Represents the various elements used to create HTTP request URIs
# for QnA Maker operations.
# From Publish Page
# Example: YOUR-RESOURCE-NAME.azurewebsites.net
# CAUTION: This is not the exact value of HOST field
# HOST trimmed to work with http library
host = "YOUR-RESOURCE-NAME.azurewebsites.net";

# Authorization endpoint key
# From Publish Page
endpoint_key = "xxx";

# Management APIs postpend the version to the route
# From Publish Page
# Example: /knowledgebases/ZZZ15f8c-d01b-4698-a2de-85b0dbf3358c/generateAnswer
# CAUTION: This is not the exact value after POST
# Part of HOST is prepended to route to work with http library
route = "";

# JSON format for passing question to service
question = "{'question': '天空为什么是蓝色的','top': 3}"
encodedQuestion = question.encode("utf-8")
print(encodedQuestion)

headers = {
  'Authorization': 'EndpointKey ' + endpoint_key,
  'Content-Type': 'application/json'
}

try:
  conn = http.client.HTTPSConnection(host, port=443)
  conn.request("POST", route, encodedQuestion, headers)

  response = conn.getresponse ()

  answer = response.read()
  print(json.dumps(json.loads(answer, encoding="utf-8"), ensure_ascii=False, indent=4))

except:
    print ("Unexpected error:", sys.exc_info()[0])
    print ("Unexpected error:", sys.exc_info()[1])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值