我向网络服务器上的 php 脚本发送了一个获取请求,该脚本返回 3 行文本。我像这样处理来自服务器的响应:
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
比我解析这样的行:
line = "";
while ((line = rd.readLine()) != null) {
String a = line.substring(0, line.indexOf('_'));
String b = line.substring(line.indexOf('_') + 1);
}
这不断抛出 StringIndexOutOfBounds 异常,我真的不明白为什么。我已经在我的项目的其他地方使用了类似的方法(使用不同的 PHP 脚本返回不同的文本行和不同的解析)并且它工作得非常好。当我记录返回的行以查看它们是否从服务器正确返回时,它们与 PHP 脚本发送的行相同。
这是有趣的部分。当我变得非常绝望时,我尝试使用以下方法测量线:
int l = line.length();
这用我的线路返回了 11。比,当我只是尝试使用以下方式显示某些内容时:
line.charAt(5);
它抛出了 StringIndexOutOfBoundsException: 5。我真的不知道这有什么问题。有人有想法吗?谢谢!
编辑
这是 PHP 脚本
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)) {
print("{$row['id']}\n{$row['number']}\n");
}
这是我的java代码:
while ((line = rd.readLine()) != null) {
Log.v("connection - user list", line); //This line logs: 1_485963
//But this doesent work
String a = line.substring(0, line.indexOf('_'));
String b = line.substring(line.indexOf('_') + 1);
}