cURL 在访问 GitHub /search/users API 时工作,但使用 restTemplate.excha



我定义了一个 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

并返回 [] 作为项目(响应正文的一部分(

而如果我将相同的 URI 与 cURL 一起使用,它会给我四个响应。

我找不到我的错。

在评论中使用OP进行调查,我们发现他没有使用与curl相同的java网址,因此他得到了不同的结果。

他正在运行此命令:

$ curl https://api.github.com/search/users?q=fullname:shiva tiwari+location:bangalore
{
"total_count": 1230,
"incomplete_results": false,
"items": [
{
"login": "Shiva108",
"id": 13223532,
...

它生成一个输出,其中包含"items"数组中的多个对象,而使用 Java 代码时,他得到了一个空的"items"数组。

URL 中' '空格字符至关重要! shell 使用空格来分隔命令的参数,当它们位于参数内时,需要正确转义它们。

OPcurl使用的url实际上只是https://api.github.com/search/users?q=fullname:shiva,最后一部分被解释为curl的另一个参数(并且也产生了错误curl: (3) URL using bad/illegal format or missing URL(,而Java正在使用完整的URL,包括姓氏和位置过滤器。

url 内' '的文字空格也是非法字符,需要使用+%20进行编码(参见百分比编码(,实际上,如果我们使用引号'来转义 shell 中的空格,我们会得到"400 错误请求":

$ curl -v 'https://api.github.com/search/users?q=fullname:shiva tiwari+location:bangalore'
...
< HTTP/1.0 400 Bad Request
...

但是通过适当的空间编码,我们得到与Java相同的结果(空的"items"数组(:

$ curl 'https://api.github.com/search/users?q=fullname:shiva+tiwari+location:bangalore'
{
"total_count": 0,
"incomplete_results": false,
"items": [
]
}
$

(我很确定java代码会自动处理空格编码(

最新更新