Example usage for com.squareup.okhttp Request.Builder Request.Builder

List of usage examples for com.squareup.okhttp Request.Builder Request.Builder

Introduction

In this page you can find the example usage for com.squareup.okhttp Request.Builder Request.Builder.

Prototype

Request.Builder

Source Link

Usage

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

License:Apache License

public Response doRest(String path, String requestBody, HttpVerb verb) throws IOException, RestApiException {
    OkHttpClient client = new OkHttpClient();

    Optional<String> gerritAuthOptional = updateGerritAuthWhenRequired(client);

    String uri = authData.getHost();
    // only use /a when http login is required (i.e. we haven't got a gerrit-auth cookie)
    // it would work in most cases also with /a, but it breaks with HTTP digest auth ("Forbidden" returned)
    if (authData.isLoginAndPasswordAvailable() && !gerritAuthOptional.isPresent()) {
        uri += "/a";
    }/* w w  w.j  ava  2  s  . c  om*/
    uri += path;

    Request.Builder builder = new Request.Builder().url(uri).addHeader("Accept", MEDIA_TYPE_JSON.toString());

    if (verb == HttpVerb.GET) {
        builder = builder.get();
    } else if (verb == HttpVerb.DELETE) {
        builder = builder.delete();
    } else {
        if (requestBody == null) {
            builder.method(verb.toString(), null);
        } else {
            builder.method(verb.toString(), RequestBody.create(MEDIA_TYPE_JSON, requestBody));
        }
    }

    if (gerritAuthOptional.isPresent()) {
        builder.addHeader("X-Gerrit-Auth", gerritAuthOptional.get());
    }

    return httpRequestExecutor.execute(client, builder);
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

License:Apache License

/**
 * Handles LDAP auth (but not LDAP_HTTP) which uses a HTML form.
 *///from   w ww  .j av  a2 s. c  o m
private Optional<String> tryGerritHttpFormAuth(OkHttpClient client) throws IOException {
    if (!authData.isLoginAndPasswordAvailable()) {
        return Optional.absent();
    }
    String loginUrl = authData.getHost() + "/login/";
    RequestBody formBody = new FormEncodingBuilder().add("username", authData.getLogin())
            .add("password", authData.getPassword()).build();

    Request.Builder builder = new Request.Builder().url(loginUrl).post(formBody);
    Response loginResponse = httpRequestExecutor.execute(client, builder);
    return extractGerritAuth(loginResponse);
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

License:Apache License

/**
 * Try to authenticate against Gerrit instances with HTTP auth (not OAuth or something like that).
 * In case of success we get a GerritAccount cookie. In that case no more login credentials need to be sent as
 * long as we use the *same* HTTP client. Even requests against authenticated rest api (/a) will be processed
 * with the GerritAccount cookie./* w w  w  . j  a  v  a  2s.c  o m*/
 *
 * This is a workaround for "double" HTTP authentication (i.e. reverse proxy *and* Gerrit do HTTP authentication
 * for rest api (/a)).
 *
 * Following old notes from README about the issue:
 * If you have correctly set up a HTTP Password in Gerrit, but still have authentication issues, your Gerrit instance
 * might be behind a HTTP Reverse Proxy (like Nginx or Apache) with enabled HTTP Authentication. You can identify that if
 * you have to enter an username and password (browser password request) for opening the Gerrit web interface. Since this
 * plugin uses Gerrit REST API (with authentication enabled), you need to tell your system administrator that he should
 * disable HTTP Authentication for any request to <code>/a</code> path (e.g. https://git.example.com/a). For these requests
 * HTTP Authentication is done by Gerrit (double HTTP Authentication will not work). For more information see
 * [Gerrit documentation].
 * [Gerrit documentation]: https://gerrit-review.googlesource.com/Documentation/rest-api.html#authentication
 */
private Optional<String> tryGerritHttpAuth(OkHttpClient client) throws IOException {
    String loginUrl = authData.getHost() + "/login/";
    Request.Builder builder = new Request.Builder().url(loginUrl).get();
    Response loginResponse = httpRequestExecutor.execute(client, builder);
    return extractGerritAuth(loginResponse);
}

From source file:com.wialon.remote.OkSdkHttpClient.java

License:Apache License

@Override
public void post(String url, Map<String, String> params, final Callback callback, int timeout) {
    Request request = new Request.Builder().url(url).post(paramsMapToRequestBody(params)).build();
    threadPool.submit(new HttpRequest(getHttpClient(timeout), request, callback));
}

From source file:com.wialon.remote.OkSdkHttpClient.java

License:Apache License

@Override
public void get(String url, Map<String, String> params, Callback callback, int timeout) {
    Request request = new Request.Builder().url(getUrlWithQueryString(url, params)).get().build();
    threadPool.submit(new HttpRequest(getHttpClient(timeout), request, callback));
}

From source file:com.wialon.remote.OkSdkHttpClient.java

License:Apache License

@Override
public void postFile(String url, Map<String, String> params, Callback callback, int timeout, File file) {
    //Method will work at 2.1 version of library https://github.com/square/okhttp/issues/963 and https://github.com/square/okhttp/pull/969
    MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    RequestBody paramsBody = paramsMapToRequestBody(params);
    if (paramsBody != null) {
        builder.addPart(paramsBody);/*  w  w w  .j  a  v a 2  s. com*/
    }
    builder.addPart(RequestBody.create(MediaType.parse(""), file));
    Request request = new Request.Builder().url(url).post(builder.build()).build();
    threadPool.submit(new HttpRequest(getHttpClient(timeout), request, callback));
}

From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java

License:Open Source License

private Request createRequestFor(String relativeUrl) {
    try {//from  ww w  .ja v  a2  s  . c  om
        URL url = createSensibleURL(relativeUrl, serverUrl);

        return new Request.Builder().url(url).header("User-Agent", getUserAgent())
                .header("Accept", APPLICATION_JSON_UTF_8).header("Authorization", createCredentials()).build();

    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(e);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java

License:Open Source License

@Override
public void uploadTestRun(String testSpecificationId, FilePath workspace, String includes, String excludes,
        Map<String, Object> metadata, PrintStream logger) throws IOException, InterruptedException {
    if (testSpecificationId == null || testSpecificationId.isEmpty()) {
        throw new IllegalArgumentException(
                "No test specification id specified. Does the test specification still exist in XL TestView?");
    }//from   w ww.j a v  a2  s  .co m
    try {
        logInfo(logger,
                format("Collecting files from '%s' using include pattern: '%s' and exclude pattern '%s'",
                        workspace.getRemote(), includes, excludes));

        DirScanner scanner = new DirScanner.Glob(includes, excludes);

        ObjectMapper objectMapper = new ObjectMapper();

        RequestBody body = new MultipartBuilder().type(MultipartBuilder.MIXED)
                .addPart(RequestBody.create(MediaType.parse(APPLICATION_JSON_UTF_8),
                        objectMapper.writeValueAsString(metadata)))
                .addPart(new ZipRequestBody(workspace, scanner, logger)).build();

        Request request = new Request.Builder()
                .url(createSensibleURL(API_IMPORT + "/" + testSpecificationId, serverUrl))
                .header("User-Agent", getUserAgent()).header("Accept", APPLICATION_JSON_UTF_8)
                .header("Authorization", createCredentials()).header("Transfer-Encoding", "chunked").post(body)
                .build();

        Response response = client.newCall(request).execute();
        ObjectMapper mapper = createMapper();
        ImportError importError;
        switch (response.code()) {
        case 200:
            logInfo(logger, "Sent data successfully");
            return;
        case 304:
            logWarn(logger, "No new results were detected. Nothing was imported.");
            throw new IllegalStateException("No new results were detected. Nothing was imported.");
        case 400:
            importError = mapper.readValue(response.body().byteStream(), ImportError.class);
            throw new IllegalStateException(importError.getMessage());
        case 401:
            throw new AuthenticationException(String.format(
                    "User '%s' and the supplied password are unable to log in", credentials.getUsername()));
        case 402:
            throw new PaymentRequiredException("The XL TestView server does not have a valid license");
        case 404:
            throw new ConnectionException("Cannot find test specification '" + testSpecificationId
                    + ". Please check if the XL TestView server is "
                    + "running and the test specification exists.");
        case 422:
            logWarn(logger, "Unable to process results.");
            logWarn(logger,
                    "Are you sure your include/exclude pattern provides all needed files for the test tool?");
            importError = mapper.readValue(response.body().byteStream(), ImportError.class);
            throw new IllegalStateException(importError.getMessage());
        default:
            throw new IllegalStateException("Unknown error. Status code: " + response.code()
                    + ". Response message: " + response.toString());
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        e.printStackTrace();
        LOG.warn("I/O error uploading test run data to {} {}\n{}", serverUrl.toString(), e.toString(), e);
        throw new IOException(
                "I/O error uploading test run data to " + serverUrl.toString() + " " + e.toString(), e);
    }
}

From source file:es.bsc.power_button_presser.httpClient.HttpClient.java

License:Open Source License

public String get(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

From source file:es.bsc.power_button_presser.httpClient.HttpClient.java

License:Open Source License

public String put(String url) throws IOException {
    Request request = new Request.Builder().url(url).put(RequestBody.create(JSON, "")).build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}