Example usage for com.squareup.okhttp Credentials basic

List of usage examples for com.squareup.okhttp Credentials basic

Introduction

In this page you can find the example usage for com.squareup.okhttp Credentials basic.

Prototype

public static String basic(String userName, String password) 

Source Link

Document

Returns an auth credential for the Basic scheme.

Usage

From source file:co.paralleluniverse.fibers.okhttp.CallTest.java

License:Open Source License

@Test
public void redirectsDoNotIncludeTooManyAuthHeaders() throws Exception {
    server2.enqueue(new MockResponse().setBody("Page 2"));
    server.enqueue(new MockResponse().setResponseCode(401));
    server.enqueue(new MockResponse().setResponseCode(302).addHeader("Location: " + server2.getUrl("/b")));

    client.setAuthenticator(new RecordingOkAuthenticator(Credentials.basic("jesse", "secret")));

    Request request = new Request.Builder().url(server.getUrl("/a")).build();
    Response response = FiberOkHttpUtil.executeInFiber(client, request);
    assertEquals("Page 2", response.body().string());

    RecordedRequest redirectRequest = server2.takeRequest();
    assertNull(redirectRequest.getHeader("Authorization"));
    assertEquals("/b", redirectRequest.getPath());
}

From source file:com.abiquo.apiclient.auth.BasicAuthentication.java

License:Apache License

public static BasicAuthentication basic(final String username, final String password) {
    return new BasicAuthentication(Credentials.basic(checkNotNull(username, "username cannot be null"),
            checkNotNull(password, "password cannot be null")));
}

From source file:com.anony.okhttp.sample.Authenticate.java

License:Apache License

public void run() throws Exception {
    client.setAuthenticator(new Authenticator() {
        @Override// w  ww. j a  v  a  2  s.  c o  m
        public Request authenticate(Proxy proxy, Response response) {
            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) {
            return null; // Null indicates no attempt to authenticate.
        }
    });

    Request request = new Request.Builder().url("http://publicobject.com/secrets/hellosecret.txt").build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

From source file:com.cuddlesoft.norilib.clients.DanbooruLegacy.java

/**
 * Create a new Danbooru 1.x client with authentication.
 *
 * @param endpoint URL to the HTTP API Endpoint - the server implementing the API.
 * @param username Username used for authentication.
 * @param password Password used for authentication.
 *///from w  w  w.j  a  va 2s  .  c  o  m
public DanbooruLegacy(String name, String endpoint, String username, String password) {
    this.name = name;
    this.apiEndpoint = endpoint;
    this.username = username;
    this.password = password;

    // Enable HTTP basic authentication.
    okHttpClient.setAuthenticator(new Authenticator() {
        @Override
        public Request authenticate(Proxy proxy, Response response) throws IOException {
            final String credential = Credentials.basic(DanbooruLegacy.this.username,
                    DanbooruLegacy.this.password);
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
            return null;
        }
    });
}

From source file:com.digi.wva.internal.HttpClient.java

License:Mozilla Public License

/**
 * Sets the basic authentication parameters to be added to every HTTP request made by this client.
 *
 * @param username the username for authentication
 * @param password the password for authentication
 *//*from ww  w .j av  a 2  s .  c  o m*/
public void useBasicAuth(String username, String password) {
    credentials = Credentials.basic(username, password);
}

From source file:com.github.drrb.surefiresplitter.go.GoServer.java

License:Open Source License

private ResponseBody get(String url) throws CommunicationError {
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    if (username != null && password != null) {
        requestBuilder.addHeader("Authorization", Credentials.basic(username, password));
    }/*from   ww w.  j  a va  2 s  .c o m*/
    Response response = execute(requestBuilder.build());
    if (response.isSuccessful()) {
        return response.body();
    } else {
        String errorMessage = String.format("Bad status code when requesting: %s (%d: %s)", url,
                response.code(), response.message());
        try (ResponseBody responseBody = response.body()) {
            errorMessage += ("\n" + responseBody.string());
        } catch (IOException e) {
            errorMessage += ". Tried to read the response body for a helpful message, but couldn't (Error was '"
                    + e.getMessage() + "').";
        }
        throw new CommunicationError(errorMessage);
    }
}

From source file:com.github.radium226.github.maven.AssetWagon.java

License:Apache License

@Override
public void doConnect(Optional<AuthenticationInfo> authenticationInfo) throws ConnectionException {
    try {/*from  w  ww  .  j a v  a  2  s  . c o m*/
        // GitHub Authentication
        GitHubBuilder gitHubBuilder = new GitHubBuilder();
        if (authenticationInfo.isPresent()) {
            String login = authenticationInfo.get().getUserName();
            String password = authenticationInfo.get().getPassword();
            if (password.startsWith("oauth2_token:")) {
                gitHubBuilder = gitHubBuilder.withOAuthToken(password.substring("oauth2_otken:".length()));
            } else {
                gitHubBuilder = gitHubBuilder.withPassword(login, password);
            }
        }

        // Proxy Authentication
        okHttpClient = new OkHttpClient();
        ProxyInfo proxyInfo = getProxyInfoByType("http");
        if (proxyInfo != null) {
            okHttpClient.setProxy(ProxyInfos.asProxy(proxyInfo));
            final String userName = proxyInfo.getUserName();
            final String password = proxyInfo.getPassword();
            if (userName != null && password != null) {
                okHttpClient.setAuthenticator(new Authenticator() {

                    @Override
                    public Request authenticateProxy(Proxy proxy, Response response) {
                        return response.request();
                    }

                    @Override
                    public Request authenticate(Proxy proxy, Response response) throws IOException {
                        String credentials = Credentials.basic(userName, password);
                        return response.request().newBuilder().header("Proxy-Authorization", credentials)
                                .build();
                    }

                });
            }
        }
        gitHub = gitHubBuilder.withConnector(new OkHttpConnector(new OkUrlFactory(okHttpClient))).build();

        this.gitHubService = GitHubService.forGitHub(gitHub).withHttpClient(okHttpClient);

        GHMyself myself = gitHub.getMyself();
        LOGGER.info("Connected as {}", myself.getName());
    } catch (IOException e) {
        throw new ConnectionException("Unable to connect to GitHub", e);
    }

}

From source file:com.horntell.http.Request.java

Response doGetRequest(String url) throws IOException {

    String credential = Credentials.basic(App.getKey(), App.getSecret());

    com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(url)
            .header("Authorization", credential)
            .addHeader("Accept", "application/vnd.horntell." + App.getVersion() + "+json")
            .addHeader("Content-Type", "text/json").build();

    com.squareup.okhttp.Response response = client.newCall(request).execute();

    return new Response(response);

}

From source file:com.horntell.http.Request.java

private Response doPostRequest(String url, Map<String, Object> params) throws IOException {

    String credential = Credentials.basic(App.getKey(), App.getSecret());
    String json = new JSONObject(params).toString();

    RequestBody body = RequestBody.create(JSON, json);
    com.squareup.okhttp.Request request;
    request = new com.squareup.okhttp.Request.Builder().url(url).header("Authorization", credential)
            .addHeader("Accept", "application/vnd.horntell." + App.getVersion() + "+json")
            .addHeader("Content-Type", "text/json").post(body).build();

    com.squareup.okhttp.Response response = client.newCall(request).execute();

    return new Response(response);
}

From source file:com.horntell.http.Request.java

private Response doDeleteRequest(String url) throws IOException {

    String credential = Credentials.basic(App.getKey(), App.getSecret());

    com.squareup.okhttp.Request request;
    request = new com.squareup.okhttp.Request.Builder().url(url).header("Authorization", credential)
            .addHeader("Accept", "application/vnd.horntell." + App.getVersion() + "+json")
            .addHeader("Content-Type", "text/json").delete().build();

    com.squareup.okhttp.Response response = client.newCall(request).execute();

    return new Response(response);
}