Example usage for com.squareup.okhttp FormEncodingBuilder FormEncodingBuilder

List of usage examples for com.squareup.okhttp FormEncodingBuilder FormEncodingBuilder

Introduction

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

Prototype

FormEncodingBuilder

Source Link

Usage

From source file:io.github.hidroh.materialistic.accounts.UserServicesClient.java

License:Apache License

@Override
public void submit(Context context, final String title, final String content, final boolean isUrl,
        final Callback callback) {
    Pair<String, String> credentials = AppUtils.getCredentials(context);
    if (credentials == null) {
        callback.onDone(false);//ww  w.j  a v a  2s .  c  om
        return;
    }
    /**
     * The flow:
     * POST /submit with acc, pw
     *  if 302 to /login, considered failed
     * POST /r with fnid, fnop, title, url or text
     *  if 302 to /newest, considered successful
     *  if 302 to /x, considered error, maybe duplicate or invalid input
     *  if 200 or anything else, considered error
     */
    // fetch submit page with given credentials
    mClient.newCall(new Request.Builder()
            .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(SUBMIT_PATH).build())
            .post(new FormEncodingBuilder().add(LOGIN_PARAM_ACCT, credentials.first)
                    .add(LOGIN_PARAM_PW, credentials.second).build())
            .build()).enqueue(new com.squareup.okhttp.Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    postError(callback);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    final boolean redirect = response.code() == HttpURLConnection.HTTP_MOVED_TEMP;
                    if (redirect) {
                        // redirect = failed login
                        postResult(callback, false);
                    } else {
                        // grab fnid from HTML and submit
                        doSubmit(title, content, getInputValue(response.body().string(), SUBMIT_PARAM_FNID),
                                isUrl, callback);
                    }
                }
            });
}

From source file:io.github.hidroh.materialistic.accounts.UserServicesClient.java

License:Apache License

@WorkerThread
private void doSubmit(String title, String content, String fnid, boolean isUrl, final Callback callback) {
    if (TextUtils.isEmpty(fnid)) {
        postError(callback);// w w w .  jav  a2  s . c o m
        return;
    }
    mClient.newCall(new Request.Builder()
            .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(SUBMIT_POST_PATH).build())
            .post(new FormEncodingBuilder().add(SUBMIT_PARAM_FNID, fnid).add(SUBMIT_PARAM_FNOP, DEFAULT_FNOP)
                    .add(SUBMIT_PARAM_TITLE, title).add(isUrl ? SUBMIT_PARAM_URL : SUBMIT_PARAM_TEXT, content)
                    .build())
            .build()).enqueue(new com.squareup.okhttp.Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    postError(callback);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    boolean redirect = response.code() == HttpURLConnection.HTTP_MOVED_TEMP;
                    if (!redirect) {
                        postError(callback);
                        return;
                    }
                    String location = response.header(HEADER_LOCATION);
                    switch (location) {
                    case DEFAULT_SUBMIT_REDIRECT:
                        postResult(callback, true);
                        break;
                    default:
                        postError(callback);
                        break;
                    }
                }
            });
}

From source file:io.kodokojo.brick.jenkins.JenkinsConfigurer.java

License:Open Source License

private BrickConfigurerData executeGroovyScript(BrickConfigurerData brickConfigurerData,
        VelocityContext context, String templatePath) {
    String url = brickConfigurerData.getEntrypoint() + SCRIPT_URL_SUFFIX;
    OkHttpClient httpClient = new OkHttpClient();
    Response response = null;// w w w. j  a v  a 2s .c  o  m
    try {
        VelocityEngine ve = new VelocityEngine();
        ve.init(VE_PROPERTIES);

        Template template = ve.getTemplate(templatePath);

        StringWriter sw = new StringWriter();
        template.merge(context, sw);
        String script = sw.toString();

        RequestBody body = new FormEncodingBuilder().add(SCRIPT_KEY, script).build();

        Request.Builder builder = new Request.Builder().url(url).post(body);
        User admin = brickConfigurerData.getDefaultAdmin();
        String crendential = String.format("%s:%s", admin.getUsername(), admin.getPassword());
        builder.addHeader("Authorization",
                "Basic " + Base64.getEncoder().encodeToString(crendential.getBytes()));
        Request request = builder.build();
        response = httpClient.newCall(request).execute();
        if (response.code() >= 200 && response.code() < 300) {
            return brickConfigurerData;
        }
        throw new RuntimeException("Unable to configure Jenkins " + brickConfigurerData.getEntrypoint()
                + ". Jenkins return " + response.code());//Create a dedicate Exception instead.
    } catch (IOException e) {
        throw new RuntimeException("Unable to configure Jenkins " + brickConfigurerData.getEntrypoint(), e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
}

From source file:io.macgyver.plugin.cloud.cloudstack.CloudStackClientImpl.java

License:Apache License

public JsonNode login(String username, String password) {

    try {//from  w w  w  . j  a  v  a  2 s . co  m
        OkRestResponse rr = target
                .post(new FormEncodingBuilder().add("username", username).add("password", password)
                        .add("response", "json").add("domain", "/").add("command", "login").build())
                .execute();

        if (rr.response().isSuccessful()) {

            ObjectNode sessionData = (ObjectNode) new ObjectMapper().readTree(rr.response().body().bytes());

            String x = rr.response().header("Set-Cookie");
            Matcher m = Pattern.compile("JSESSIONID=(.*);.*").matcher(x);
            if (m.matches()) {
                sessionData.put("JSESSIONID", m.group(1));
            }

            return sessionData;
        } else {
            throw new OkRestException(rr.response().code());
        }
    } catch (IOException e) {
        throw new OkRestWrapperException(e);
    }

}

From source file:io.macgyver.plugin.cloud.cloudstack.RequestBuilder.java

License:Apache License

public JsonNode execute() {

    try {/*from   ww w . j  ava  2s . c  om*/
        OkRestTarget t = client.target;
        param("response", "json");

        String expires = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ")
                .print(System.currentTimeMillis() + 1000 * 60 * 5);
        param("expires", expires);
        FormEncodingBuilder b = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            b = b.add(entry.getKey(), entry.getValue());

        }

        if (client.usernamePasswordAuth) {
            String sessionKey = client.getSessionData().path("loginresponse").path("sessionkey").asText();

            b = b.add("sessionkey", sessionKey).add("expires", expires).add("signatureversion", "3");

            t = t.header("Cookie", "JSESSIONID=" + client.getSessionData().path("JSESSIONID").asText());

        } else {
            b = b.add("apiKey", client.apiKey).add("signature", computeSignature());

        }

        return t.post(b.build()).execute(JsonNode.class);
    } catch (ExecutionException e) {
        throw new MacGyverException(e);
    }
}

From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java

License:Apache License

/**
 * Performs an authentication, caches the resulting authentication token,
 * and returns it./* w ww . jav  a  2 s .c  o  m*/
 *
 * @return
 */
public String authenticate() {

    try {
        FormEncodingBuilder b = new FormEncodingBuilder();
        b = b.add("username", username).add("password", password).add("format", "json").add("method",
                "authenticate");

        Request r = new Request.Builder().url(getUrl()).addHeader("Accept", "application/json").post(b.build())
                .build();
        Response resp = getClient().newCall(r).execute();

        ObjectNode obj = parseJsonResponse(resp, "authenticate");

        String sid = obj.path("session_id").asText();
        if (Strings.isNullOrEmpty(sid)) {
            throw new ElbException("authentication failed");
        }
        tokenCache.put(A10_AUTH_TOKEN_KEY, sid);
        return sid;

    } catch (IOException e) {
        throw new ElbException(e);
    }

}

From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java

License:Apache License

public Response execute(RequestBuilder b) {
    try {/*from w ww .ja  v  a 2 s .  c  o m*/

        String method = b.getMethod();
        Preconditions.checkArgument(!Strings.isNullOrEmpty(method), "method argument must be passed");

        String url = null;

        Response resp;
        String format = b.getParams().getOrDefault("format", "xml");
        b = b.param("format", format);
        if (!b.hasBody()) {

            url = formatUrl(b.getParams(), format);
            FormEncodingBuilder fb = new FormEncodingBuilder().add("session_id", getAuthToken());
            for (Map.Entry<String, String> entry : b.getParams().entrySet()) {
                if (!entry.getValue().equals("format")) {
                    fb = fb.add(entry.getKey(), entry.getValue());
                }
            }
            resp = getClient().newCall(new Request.Builder().url(getUrl()).post(fb.build()).build()).execute();
        } else if (b.getXmlBody().isPresent()) {
            b = b.param("format", "xml");
            url = formatUrl(b.getParams(), "xml");
            String bodyAsString = new XMLOutputter(Format.getRawFormat()).outputString(b.getXmlBody().get());
            final MediaType XML = MediaType.parse("text/xml");

            resp = getClient().newCall(new Request.Builder().url(url)
                    .post(RequestBody.create(XML, bodyAsString)).header("Content-Type", "text/xml").build())
                    .execute();
        } else if (b.getJsonBody().isPresent()) {
            b = b.param("format", "json");
            url = formatUrl(b.getParams(), "json");
            String bodyAsString = mapper.writeValueAsString(b.getJsonBody().get());

            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            resp = getClient().newCall(new Request.Builder().url(url).post(

                    RequestBody.create(JSON, bodyAsString)).header("Content-Type", "application/json").build())
                    .execute();
        } else {
            throw new UnsupportedOperationException("body type not supported");
        }
        // the A10 API rather stupidly uses 200 responses even when there is
        // an error
        if (!resp.isSuccessful()) {
            logger.warn("response code={}", resp.code());
        }

        return resp;

    } catch (IOException e) {
        throw new ElbException(e);
    }
}

From source file:jp.co.ipublishing.esnavi.impl.user.UserClient.java

License:Apache License

@NonNull
@Override// w  w w  .  j  av  a 2 s. c  om
public Observable<Void> registerNotificationKey(@NonNull final String key) {
    return Observable.create(new Observable.OnSubscribe<Void>() {
        @Override
        public void call(Subscriber<? super Void> subscriber) {
            // ?????????????????????
            final String latestKey = getRegistrationId(mContext);

            if (!key.equals(latestKey)) {
                try {
                    final ApiMethod apiMethod = mApi.registerNotificationKey();

                    final RequestBody formBody = new FormEncodingBuilder().add("gcmid", key).build();

                    final Request request = new Request.Builder().url(apiMethod.getUrl()).post(formBody)
                            .build();

                    mClient.newCall(request).execute();

                    storeRegistrationId(mContext, key);

                    subscriber.onNext(null);
                    subscriber.onCompleted();

                } catch (IOException e) {
                    Log.e(TAG, ExceptionUtils.getStackTrace(e));

                    subscriber.onError(e);
                }
            } else {
                subscriber.onNext(null);
                subscriber.onCompleted();
            }
        }
    });
}

From source file:Logica.Flask.java

public static String sendText(String informacion, String tipo) {

    RequestBody formBody = new FormEncodingBuilder().add("tipo", tipo).add("informacion", informacion).build();
    String r = getString("Matriz", formBody);
    return r;//w w w.j a v  a2s. c om
}

From source file:Logica.Flask.java

public static String sendText(String usuario, String empresa, String departamento, String tipo) {

    RequestBody formBody = new FormEncodingBuilder().add("tipo", tipo).add("usuario", usuario)
            .add("empresa", empresa).add("departamento", departamento).build();
    String r = getString("Matriz", formBody);
    return r;//from w w  w  .j a  va 2  s.c o  m
}