Example usage for com.squareup.okhttp FormEncodingBuilder build

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

Introduction

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

Prototype

public RequestBody build() 

Source Link

Usage

From source file:com.yingke.shengtai.adapter.ChatAllHistoryAdapter.java

License:Open Source License

public void postRequest(final TextView text, final String userName, final Map<String, String> map) {
    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        builder.add(entry.getKey(), entry.getValue());
    }/*w  w w. j  ava 2 s . c o m*/
    RequestBody formBody = builder.build();
    Request request = new Request.Builder().url(IApi.URL_IMID_NAME).header("User-Agent", "OkHttp Headers.java")
            .addHeader("Accept", "application/json").addHeader("Content-Type", "application/json;charset=utf-8")
            .addHeader("Content-Length", "length").post(formBody).build();
    RequestManager.getOkHttpClient().newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String json = response.body().string();
                ImidToNickNameData data = JosnUtil.gson.fromJson(json, new TypeToken<ImidToNickNameData>() {
                }.getType());
                if (data != null && TextUtils.equals("1", "1")) {
                    try {

                        User user = new User();
                        user.setNick(data.getDetaillist().get(0).getDisplayname());
                        user.setUsername(data.getDetaillist().get(0).getImid());
                        user.setSex(data.getDetaillist().get(0).getSex());
                        userDao.saveContactsss(user);
                        UIHandler.sendEmptyMessage(0);
                    } catch (Exception e) {

                    }
                }

            }

        }
    });
}

From source file:com.yingke.shengtai.adapter.ChatSaleAdapter.java

License:Open Source License

public void postRequest(final TextView text, final String userName, final Map<String, String> map) {
    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        builder.add(entry.getKey(), entry.getValue());
    }/*w w w  .j ava 2 s .c o m*/
    RequestBody formBody = builder.build();
    Request request = new Request.Builder().url(IApi.URL_IMID_NAME).header("User-Agent", "OkHttp Headers.java")
            .addHeader("Accept", "application/json").addHeader("Content-Type", "application/json;charset=utf-8")
            .addHeader("Content-Length", "length").post(formBody).build();
    RequestManager.getOkHttpClient().newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String json = response.body().string();
                ImidToNickNameData data = JosnUtil.gson.fromJson(json, new TypeToken<ImidToNickNameData>() {
                }.getType());
                if (data != null && TextUtils.equals("1", data.getResult() + "")) {
                    try {
                        User user = new User();
                        user.setNick(data.getDetaillist().get(0).getDisplayname());
                        user.setUsername(data.getDetaillist().get(0).getImid());
                        user.setSex(data.getDetaillist().get(0).getSex());
                        userDao.saveContactsss(user);
                        UIHandler.sendEmptyMessage(0);

                    } catch (Exception e) {

                    }
                }

            }

        }
    });
}

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

License:Apache License

@Override
public void login(final String username, final String password, boolean createAccount,
        final Callback callback) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder().add(LOGIN_PARAM_ACCT, username)
            .add(LOGIN_PARAM_PW, password).add(LOGIN_PARAM_GOTO, DEFAULT_REDIRECT);
    if (createAccount) {
        formBuilder.add(LOGIN_PARAM_CREATING, CREATING_TRUE);
    }// w w w  .j av a 2  s . co  m
    mClient.newCall(new Request.Builder()
            .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(LOGIN_PATH).build())
            .post(formBuilder.build()).build()).enqueue(wrap(callback));
}

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

License:Apache License

public JsonNode execute() {

    try {/*from   ww w.  j av  a2  s  .co  m*/
        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.//from   www .  j a  v a2s.  co 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   ww  w.  j  a va  2 s.co  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:net.codestory.rest.misc.PostBody.java

License:Apache License

public static RequestBody form(String firstParameterName, Object firstParameterValue,
        Object... parameterNameValuePairs) {
    FormEncodingBuilder form = new FormEncodingBuilder();

    form.add(firstParameterName, firstParameterValue.toString());
    for (int i = 0; i < parameterNameValuePairs.length; i += 2) {
        form.add(parameterNameValuePairs[i].toString(), parameterNameValuePairs[i + 1].toString());
    }//ww  w.j  a va2 s.  c o m

    return form.build();
}

From source file:net.qiujuer.common.okhttp.impl.RequestCallBuilder.java

License:Apache License

protected RequestBody createFormBody(StrParam... strParams) {
    FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
    formEncodingBuilder = buildFormBody(formEncodingBuilder);

    // Add values
    if (strParams != null && strParams.length > 0) {
        for (StrParam strParam : strParams) {
            if (strParam.key != null && strParam.value != null) {
                formEncodingBuilder.add(strParam.key, strParam.value);
                log("buildFormParam: key: " + strParam.key + " value: " + strParam.value);
            } else {
                log("buildFormParam: key: " + (strParam.key != null ? strParam.key : "null") + " value: "
                        + (strParam.value != null ? strParam.value : "null"));
            }//  w ww. ja  v  a 2  s. c  om
        }
    }
    return formEncodingBuilder.build();
}

From source file:org.addhen.birudo.data.net.JenkinsClient.java

License:Apache License

public GcmRegistrationStatus sendGcmTokenToServer() throws Exception {
    if (mJenkinsUserEntity == null) {
        return null;
    }/*from   ww w.jav a 2s .  co  m*/

    // Retrieve crumbInfo
    CrumbInfoEntity crumbInfoEntity = retrieveCrumbInfo();
    if (crumbInfoEntity != null && crumbInfoEntity.isCsrfEnabled()) {
        setHeader(crumbInfoEntity.getCrumbRequestField(), crumbInfoEntity.getCrumb());
    }

    FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();

    formEncodingBuilder.add("token", mJenkinsUserEntity.getSenderId());

    String credential = Credentials.basic(mJenkinsUserEntity.getUsername(), mJenkinsUserEntity.getToken());

    setHeader("Authorization", credential);

    setRequestBody(formEncodingBuilder.build());

    // Send to gcm/regsiter
    super.url = String.format("%sgcm/register", mJenkinsUserEntity.getUrl());
    setMethod(HttpMethod.POST);
    execute();

    final int statusCode = getResponse().code();
    GcmRegistrationStatus status = new GcmRegistrationStatus();
    status.setStatusCode(statusCode);
    if (statusCode != 200) {
        log("Sending registering token failed with satus code %s", statusCode);
        status.setStatus(false);
    } else {
        status.setStatus(true);
    }

    return status;
}

From source file:org.addhen.smssync.data.net.AppHttpClient.java

License:Open Source License

/**
 * Get HTTP Entity populated with data in a format specified by the current sync scheme
 */// www. j a v  a  2s. c om
private void setHttpEntity(SyncScheme.SyncDataFormat format) throws Exception {
    RequestBody body;
    switch (format) {
    case JSON:
        body = RequestBody.create(JSON, DataFormatUtil.makeJSONString(getParams()));
        log("setHttpEntity format JSON");
        break;
    case XML:
        body = RequestBody.create(XML, DataFormatUtil.makeXMLString(getParams(), "payload", UTF_8.name()));
        log("setHttpEntity format XML");
        break;
    case URLEncoded:
        log("setHttpEntity format URLEncoded");
        FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
        List<HttpNameValuePair> params = getParams();
        for (HttpNameValuePair pair : params) {
            formEncodingBuilder.add(pair.getName(), pair.getValue());
        }
        body = formEncodingBuilder.build();
        break;
    default:
        throw new Exception("Invalid data format");
    }
    setRequestBody(body);
}