【发布时间】:2020-06-29 16:30:33
【问题描述】:
我已经定义了一个 RestTemplate 支持的 HttpClient 来调用 Github API 来搜索用户
我的方法是这样的
public List<User> fetchPublicInformation(String firstName, String lastName, String location) {
final HttpHeaders headers = new HttpHeaders();
if (token != null && token.length() != 0) {
headers.set("Authorization", "bearer " + token);
}
headers.set("'User-Agent'", "request");
HttpEntity<String> entity = new HttpEntity<String>(headers);
synchronized (this) {
StringBuilder uri = new StringBuilder(GITHUB_SEARCH + "users?q=fullname:");
if (!firstName.isEmpty()) {
uri.append(firstName.trim().toLowerCase());
} else {
firstName = " ";
}
if (!lastName.isEmpty()) {
uri.append(" " + lastName.trim().toLowerCase());
} else {
lastName = " ";
}
if (location != null && !location.isEmpty()) {
uri.append("+location:" + location.trim().toLowerCase());
}
System.out.println(uri.toString());
ResponseEntity<GitHubUsersResponse> response = null;
response = template.exchange(uri.toString(), HttpMethod.GET, entity, GitHubUsersResponse.class);
return response.getBody().getItems();
}
}
此方法命中 URI
https://api.github.com/search/users?q=fullname:shiva tiwari+location:bangalore
并返回 [] 作为项目(响应正文的一部分)
如果我使用与 cURL 相同的 URI,它会给我四个响应。
我找不到我的错。
【问题讨论】:
-
如果我使用您在
curl(curl 'https://api.github.com/search/users?q=fullname:shiva tiwari+location:bangalore') 发布的 uri,我会收到“400 Bad Request”,我相信是因为“shiva tiwari”中的空格字符' '。如果我用+或%20替换空格,我会得到一个带有“items”属性的json 对象,其中包含[](空数组)。如果我使用浏览器,结果相同。 -
如果我在 macOS 终端中执行“curl api.github.com/search/users?q=fullname:shivatiwari+location:bangalore”,我会得到有效的结果
-
@MarcoLucidi 我认为我们不需要 curl 2 次span>
-
你不需要“
curl2 次”,我将运行的命令放在圆括号 () 中。尝试运行此命令:curl 'https://api.github.com/search/users?q=fullname:shiva tiwari+location:bangalore'。你得到了什么?现在试试这个:curl 'https://api.github.com/search/users?q=fullname:shiva+tiwari+location:bangalore'。你得到了什么? -
你得到这个结果是因为我在第一条评论中提到的 url 中的空格! curl 没有使用完整的 url,而只是
https://api.github.com/search/users?q=fullname:shiva并且与 java 使用的 url 不同。尝试我之前告诉你的两个命令:第一个会失败(我收到 400 bad request),第二个会报告与 java 相同的结果(items: [])。空格用于分隔 shell 中的参数,需要正确转义。
标签: java spring curl github-api resttemplate