使用Java和async-http-client进行基本身份验证的URL内容

rod*_*ves 2 java asynchttpclient

我正在编写Java lib并且需要对URL执行请求 - 当前使用ning的async-http-client - 并获取其内容.所以我有一个get方法返回获取文档内容的String.但是,为了能够获得它,我必须执行HTTP基本身份验证,并且我在Java代码中没有成功:

public String get(String token) throws IOException {
    String fetchURL = "https://www.eventick.com.br/api/v1/events/492";

    try {
        String encoded = URLEncoder.encode(token + ":", "UTF-8");
        return this.asyncClient.prepareGet(fetchURL)
        .addHeader("Authorization", "Basic " + encoded).execute().get().getResponseBody();
    }
}
Run Code Online (Sandbox Code Playgroud)

代码不返回任何错误,它只是不提取URL,因为没有正确设置身份验证标头.

使用卷曲-u选项,我可以轻松获得我想要的东西:

curl https://www.eventick.com.br/api/v1/events/492 -u 'xxxxxxxxxxxxxxx:'

返回:

{"events":[{"id":492,"title":"Festa da Bagaceira","venue":"Mangueirão de Paulista",
"slug":"bagaceira-fest", "start_at":"2012-07-29T16:00:00-03:00",
"links":{"tickets":[{"id":738,"name":"Normal"}]}}]}
Run Code Online (Sandbox Code Playgroud)

如何在Java中完成?使用async-http-client lib?或者,如果您知道如何使用其他方式...

欢迎任何帮助!

Kir*_*rby 6

你很亲密 您需要基于64位编码而不是URL编码.也就是说,你需要

String encoded = Base64.getEncoder().encodeToString((user + ':' + password).getBytes(StandardCharsets.UTF_8));
Run Code Online (Sandbox Code Playgroud)

而不是

String encoded = URLEncoder.encode(token + ":", "UTF-8");
Run Code Online (Sandbox Code Playgroud)

(请注意,为了别人的利益,因为我回答2年后,在我的回答中我使用的是更标准的"user:password"而你的问题有"token:".如果"token:"你需要的话,那就坚持下去.但也许这是这个问题呢?)

这是一个简短,独立,正确的例子

package so17380731;

import com.ning.http.client.AsyncHttpClient;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.ws.rs.core.HttpHeaders;

public class BasicAuth {

    public static void main(String... args) throws Exception {
        try(AsyncHttpClient asyncClient = new AsyncHttpClient()) {
            final String user = "StackOverflow";
            final String password = "17380731";
            final String fetchURL = "https://www.eventick.com.br/api/v1/events/492";
            final String encoded = Base64.getEncoder().encodeToString((user + ':' + password).getBytes(StandardCharsets.UTF_8));
            final String body = asyncClient
                .prepareGet(fetchURL)
                .addHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded)
                .execute()
                .get()
                .getResponseBody(StandardCharsets.UTF_8.name());
            System.out.println(body);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)