基本上,我试图从API中获取字符串,而该API只是空白页面,其中一行包含所有需要的信息,而我只是在尝试获取其中的一部分。
这部分是每个人的ID-字符数相同。
API对每个人都有以下这一行:
{“ id”:“ anExampleUniqueWhichHas32Charact”,“名称”:“ Player”}
我有点更改了代码,以便您理解,因为我正在使用专用于此的库,但是我只是想使Web抓取正确。
所以我想做的是Web Scrape并获取该数量的string.length。
但这是行不通的。
我知道我也可以将Regex用于模式,但是我真的不知道如何使用它。老实说,正则表达式在这种情况下会更有帮助。
public void checkAPI() throws IOException {
String person = userInput.nextLine(); // It's just any name.
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" +
person);
URLConnection con = url.openConnection();
InputStream isr =con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(isr));
String line;
while ((line = br.readLine()) != null) {
if (line.length() == 32) {
System.out.println(line);
}
}
}
我目前只希望打印该行,稍后它将在其他工作中使用。
没有错误被抛出。
最佳答案
该API使用Json。 https://de.wikipedia.org/wiki/JavaScript_Object_Notation
您可以使用杰克逊https://en.wikipedia.org/wiki/Jackson_(API)之类的标准json解析器来解析和查询结果。
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(new URL("https://api.mojang.com/users/profiles/minecraft/KrisJelbring"));
System.out.println("Name: "+node.get("name"));
System.out.println("Id: "+node.get("id"));
但是,如果您不喜欢使用杰克逊,则可以手动完成:但这是胡说,也不是很稳定:
while ((line = br.readLine()) != null)
{
int startOfId = line.indexOf("\"id\"") + 4;
int startOfValue = line.indexOf("\"", startOfId) + 1;
int endOfValue = line.indexOf("\"", startOfValue);
System.out.println("id: " + line.substring(startOfValue, endOfValue));
}
关于java - 尝试从只有一行的网站获取字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57946658/