【发布时间】:2014-04-30 19:04:49
【问题描述】:
我正在尝试在 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 的值为 null,因此显示“Response Failed”。我已经多次查看报价,但似乎无法找到 responseContent 中的值为 null 的原因。谁能比我更有知识,请查看代码并指出我在哪里犯了错误?
【问题讨论】:
-
您的 logcat 是否显示任何异常?应该是,因为
pandorabotsRequest(String, String, String)在catch中只能返回null,spec和responseContent(string)不能返回null,只能抛出异常。尽量避免笼统地说(catch (Exception e)),但要具体
标签: java android pandorabots