快速入门:通过 Java 获取知识库中问题的答案:https://docs.microsoft.com/zh-cn/azure/cognitive-services/qnamaker/quickstarts/get-answer-from-knowledge-base-java
在运行官网 sample(https://github.com/Azure-Samples/cognitive-services-qnamaker-java/blob/master/documentation-samples/quickstarts/get-answer/GetAnswer.java)的时候,本机 curl 访问正常,IntelliJ 里 Java 代码向后台发送请求,返回表明没拿到问题:questions":[]
(py36Tensorflow14OpenCV) bash-3.2$ curl -X POST https://cocolabbot.azurewebsites.net/qnamaker/knowledgebases/423430f7-8d01-412f-a157-297169cfa664/generateAnswer -H "Authorization: EndpointKey 092ac9c5-f560-4edb-9db4-b293115e1320" -H "Content-type: application/json" -d "{'question':'天空为什么是蓝色的'}"
{"answers":[{"questions":["天空为什么是蓝色的"],"answer":"宝马车在蓝色天空下最漂亮","score":100.0,"id":2,"source":"Editorial","metadata":[],"context":{"isContextOnly":false,"prompts":[]}}],"debugInfo":null,"activeLearningEnabled":false}(py36Tensorflow14OpenCV) bash-3.2$
{"answers":[{"questions":[],"answer":"No good match found in KB.","score":0.0,"id":-1,"source":null,"metadata":[]}],"debugInfo":null,"activeLearningEnabled":false}
经过检查,发现是StringEntity格式编码问题。sample使用的Apache的httpclient发起httpPost请求,后端拿不到问题。在跟踪代码的时候,发现主要是客户端StringEntity的处理问题。StringEntity设置编码格式主要有以下两种方式
//第一种方式:后端无法解码
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params));
stringEntity.setContentType("UTF-8");
//第二种方式:请求成功
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), "UTF-8");
StringEntity源码:
public StringEntity(String string) throws UnsupportedEncodingException {
this(string, ContentType.DEFAULT_TEXT);
}
public StringEntity(String string, ContentType contentType) throws UnsupportedCharsetException {
Args.notNull(string, "Source string");
Charset charset = contentType != null ? contentType.getCharset() : null;
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
this.content = string.getBytes(charset);
if (contentType != null) {
this.setContentType(contentType.toString());
}
}
当不传入ContentType时,会使用默认值。