我正在尝试在android中制作一个聊天机器人。所以,我正在尝试将 pandorabot 与我的 android 应用程序连接起来。
public class Brain {
public String defaultCustid = "0";
public String custid = defaultCustid;
public String responseFailed = "RESPONSE FAILED";
public String defaultBotId = "da43c986ee34039e";
public String defaultHost = "http://www.pandorabots.com";
String botResponse;
public String askPandorabots(String input) {
return askPandorabots(input, defaultHost, defaultBotId);
}
public String askPandorabots(String input, String host, String botid) {
String responseContent = pandorabotsRequest(input, host, botid);
if (responseContent == null)
return responseFailed;
else
return pandorabotsResponse(responseContent, host, botid);
}
public String pandorabotsRequest(String input, String host, String botid) {
try {
String spec = spec(host, botid, custid, input);
return responseContent(spec);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public String spec(String host, String botid, String custid, String input) {
String spec = "";
try {
if (custid.equals("0")) // get custid on first transaction with Pandorabots
spec = String.format("%s?botid=%s&input=%s",
"http://" + host + "/pandora/talk-xml",
botid,
URLEncoder.encode(input, "UTF-8"));
else spec = // re-use custid on each subsequent interaction
String.format("%s?botid=%s&custid=%s&input=%s",
"http://" + host + "/pandora/talk-xml",
botid,
custid,
URLEncoder.encode(input, "UTF-8"));
} catch (Exception ex) {
ex.printStackTrace();
}
return spec;
}
public String responseContent(String url) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
InputStream is = client.execute(request).getEntity().getContent();
BufferedReader inb = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder("");
String line;
String NL = System.getProperty("line.separator");
while ((line = inb.readLine()) != null) {
sb.append(line).append(NL);
}
inb.close();
return sb.toString();
}
}
这是我用于连接的代码。但机器人总是以“响应失败”响应。
String responseContent = pandorabotsRequest(input, host, botid);
if (responseContent == null)
return responseFailed;
else
return pandorabotsResponse(responseContent, host, botid);
在这里,responseContent 的值变为空,因此显示“响应失败”。我已经多次查看报价,但似乎无法找到 responseContent 中的值为 null 的原因。谁能比我更有知识,请查看代码并指出我在哪里犯了错误?