我已经向android中的Microsoft qna makers api发了帖子请求。 但我得到以下例外:
java.io.FileNotFoundException: https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/<My KB ID>/generateAnswer
发布帖子请求的API格式:
POST /knowledgebases/<Your KB ID>/generateAnswer HTTP/1.1
Host: https://westus.api.cognitive.microsoft.com/qnamaker/v1.0
Ocp-Apim-Subscription-Key: <Your Subscription key>
Content-Type: application/json
Cache-Control: no-cache
{"question": "Question goes here"}
我只是遵循上面指定的格式,并在 getText()方法中发布了一个帖子请求。并且使用 RetrieveFeedTask 类在后台调用此方法。 这是我用来发布帖子请求的代码:
public class MainActivity extends AppCompatActivity {
Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RetrieveFeedTask task = new RetrieveFeedTask();
task.execute();
}
});
}
// Create GetText Metod
public void GetText() throws UnsupportedEncodingException {
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL("https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/<My KB Id>/generateAnswer");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Host", "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/");
conn.setRequestProperty("Ocp-Apim-Subscription-Key", "<My Ocp-Apim-Subscription-Key>");
conn.setRequestProperty("Content-Type", "application/json");
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("question", "hi");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
wr.flush();
Log.d("karma", "json is " + jsonParam);
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
Log.d("karma ", "response is " + text);
} catch (Exception ex) {
Log.d("karma", "exception at last " + ex);
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
}
class RetrieveFeedTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
try {
Log.d("karma", "called");
GetText();
Log.d("karma", "after called");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d("karma", "Exception occurred " + e);
}
return null;
}
}
}
请帮助我解决这个问题......