RESTEasy client framework authentication credentials

前端 未结 3 1826
谎友^
谎友^ 2020-12-08 03:32

RESTEasy (a JAX-RS implementation) has a nice client framework, eg:

ServiceApi client = ProxyFactory.create(ServiceApi.class, baseUri);

How

3条回答
  •  春和景丽
    2020-12-08 04:11

    Maybe something like this (with RestEasy 2.3.1) :

    //(...imports...)
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.jboss.resteasy.client.ClientRequest;
    import org.jboss.resteasy.client.ClientResponse;
    import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
    
    //(...code...)
    private static final String ENDPOINT = "the_rest_endpoint_here";
    
    String username = "";
    String password = "";
    
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
    ApacheHttpClient4Executor executer = new ApacheHttpClient4Executor(client);
    
    ClientRequest req = new ClientRequest(ENDPOINT, executer);
    
    ClientResponse res = req.get(String.class);
    System.out.println(res.getEntity());
    res.close();
    

    ...or with RestEasy 3.0.18

    //(...imports...)
    import javax.ws.rs.core.Response;
    import org.jboss.resteasy.client.jaxrs.BasicAuthentication;
    import org.jboss.resteasy.client.jaxrs.ResteasyClient;
    import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
    import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
    
    //(...code...)
    private static final String ENDPOINT = "the_rest_endpoint_here";
    
    String usertoken = "";
    String password = "";
    
    //with proxy(comment this if not using)
    ResteasyClient client = new ResteasyClientBuilder()
                .defaultProxy("my_proxy", 8080, "http")
                .build();
    
    ResteasyWebTarget target = client.target(ENDPOINT);
    target.register(new BasicAuthentication(usertoken, password));
    
    Response response = target.request().get();
    System.out.println(response.readEntity(String.class));
    response.close();
    

提交回复
热议问题