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

问题描述 投票:1回答:4

我正在编写一个Java库,需要对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();
    }
}

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

使用curl -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"}]}}]}

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

欢迎任何帮助!

java asynchttpclient
4个回答
5
投票

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

String encoded = Base64.getEncoder().encodeToString((user + ':' + password).getBytes(StandardCharsets.UTF_8));

而不是

String encoded = URLEncoder.encode(token + ":", "UTF-8");

(请注意,为了他人的利益,因为我回答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);
        }
    }
}

3
投票

文档非常粗略,但我认为您需要按照RequestBuilder javadoc中显示的模式使用Request

Request r = new RequestBuilder().setUrl("url")
    .setRealm((new Realm.RealmBuilder()).setPrincipal(user)
    .setPassword(admin)
    .setRealmName("MyRealm")
    .setScheme(Realm.AuthScheme.DIGEST).build());
r.execute();

(显然,这个例子不是Basic Auth,但是有关于你将如何做的线索。)


FWIW,您当前代码的一个问题是Basic Auth标头使用base64编码而不是URL编码;有关详细信息,请参阅RFC2617


1
投票

基本上,这样做: BoundRequestBuilder request = asyncHttpClient .preparePost(getUrl()) .setHeader("Accept", "application/json") .setHeader("Content-Type", "application/json") .setRealm(org.asynchttpclient.Dsl.basicAuthRealm(getUser(), getPassword())) // ^^^^^^^^^^^-- this is the important part .setBody(json);

测试可以在这里找到:https://github.com/AsyncHttpClient/async-http-client/blob/master/client/src/test/java/org/asynchttpclient/BasicAuthTest.java


0
投票

这也是添加Basic Authorization的另一种方法,你可以使用两个类中的任何一个来使用AsyncHttpClient,HttpClient,在这种情况下我将使用AsyncHttpClient

AsyncHttpClient client=new AsyncHttpClient();           
        Request request = client.prepareGet("https://www.eventick.com.br/api/v1/events/492").
            setHeader("Content-Type","application/json")
            .setHeader("Authorization","Basic b2pAbml1LXR2LmNvbTpnMGFRNzVDUnhzQ0ZleFQ=")
            .setBody(jsonObjectRepresentation.toString()).build();

添加标题部分后

            ListenableFuture<Response> r = null;
            //ListenableFuture<Integer> f= null;
            try{
            r = client.executeRequest(request);
            System.out.println(r.get().getResponseBody());
            }catch(IOException e){

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            client.close();

它可能对你有用

© www.soinside.com 2019 - 2024. All rights reserved.