Example usage for com.squareup.okhttp FormEncodingBuilder add

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

Introduction

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

Prototype

public FormEncodingBuilder add(String name, String value) 

Source Link

Document

Add new key-value pair.

Usage

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Build a form-encoding request body with the given form parameters.
 *
 * @param formParams Form parameters in the form of Map
 * @return RequestBody/*from  w  w w  .j av  a2 s. c o  m*/
 */
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder();
    for (Entry<String, Object> param : formParams.entrySet()) {
        formBuilder.add(param.getKey(), parameterToString(param.getValue()));
    }
    return formBuilder.build();
}

From source file:alfio.manager.system.MailgunMailer.java

License:Open Source License

private RequestBody prepareBody(Event event, String to, String subject, String text, Optional<String> html,
        Attachment... attachments) throws IOException {

    String from = event.getDisplayName() + " <" + configurationManager
            .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), MAILGUN_FROM)) + ">";

    if (ArrayUtils.isEmpty(attachments)) {
        FormEncodingBuilder builder = new FormEncodingBuilder().add("from", from).add("to", to)
                .add("subject", subject).add("text", text);

        String replyTo = configurationManager.getStringConfigValue(
                Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), "");
        if (StringUtils.isNotBlank(replyTo)) {
            builder.add("h:Reply-To", replyTo);
        }//from   w w  w. j  ava2  s  .  c om
        html.ifPresent((htmlContent) -> builder.add("html", htmlContent));
        return builder.build();

    } else {
        // https://github.com/square/okhttp/blob/parent-2.1.0/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java
        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        multipartBuilder.addFormDataPart("from", from).addFormDataPart("to", to)
                .addFormDataPart("subject", subject).addFormDataPart("text", text);

        html.ifPresent((htmlContent) -> multipartBuilder.addFormDataPart("html", htmlContent));

        for (Attachment attachment : attachments) {
            byte[] data = attachment.getSource();
            multipartBuilder.addFormDataPart("attachment", attachment.getFilename(), RequestBody
                    .create(MediaType.parse(attachment.getContentType()), Arrays.copyOf(data, data.length)));
        }
        return multipartBuilder.build();
    }
}

From source file:au.com.wallaceit.reddinator.RedditData.java

License:Open Source License

private String redditApiRequest(String urlStr, String method, int oauthMode, HashMap<String, String> formData)
        throws RedditApiException {
    String json;/*from   www .j a v  a2 s.  c  o m*/
    // create client if null
    if (httpClient == null) {
        createHttpClient();
    }
    try {
        Request.Builder httpRequest = new Request.Builder().url(urlStr);
        RequestBody httpRequestBody;
        String requestStr = "";
        if (formData != null) {
            FormEncodingBuilder formBuilder = new FormEncodingBuilder();
            Iterator iterator = formData.keySet().iterator();
            String key;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                formBuilder.add(key, formData.get(key));
            }
            httpRequestBody = formBuilder.build();
        } else {
            if (!method.equals("GET")) {
                int queryIndex = urlStr.indexOf("?");
                if (queryIndex != -1)
                    urlStr = urlStr.substring(queryIndex);
                requestStr = URLEncoder.encode(urlStr, "UTF-8");
            }
            httpRequestBody = RequestBody.create(POST_ENCODED, requestStr);
        }

        switch (method) {
        case "POST":
            httpRequest.post(httpRequestBody);
            break;
        case "PUT":
            httpRequest.put(httpRequestBody);
            break;
        case "DELETE":
            httpRequest.delete(httpRequestBody);
            break;
        case "GET":
        default:
            httpRequest.get();
            break;
        }
        if (oauthMode == REQUEST_MODE_OAUTHREQ) {
            // For oauth token retrieval and refresh
            httpRequest.addHeader("Authorization", "Basic " + Base64
                    .encodeToString((OAUTH_CLIENTID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        } else if (isLoggedIn() && oauthMode == REQUEST_MODE_AUTHED) {
            if (isTokenExpired()) {
                refreshToken();
            }
            // add auth headers
            String tokenStr = getTokenValue("token_type") + " " + getTokenValue("access_token");
            httpRequest.addHeader("Authorization", tokenStr);
        }

        Response response = httpClient.newCall(httpRequest.build()).execute();
        json = response.body().string();
        int errorCode = response.code();
        if (errorCode < 200 && errorCode > 202) {
            String errorMsg = getErrorText(json);
            throw new RedditApiException(
                    "Error " + String.valueOf(errorCode) + ": "
                            + (errorMsg.equals("") ? response.message() : errorMsg)
                            + (errorCode == 403 ? " (Authorization with Reddit required)" : ""),
                    errorCode == 403, errorCode);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RedditApiException("Error: " + e.getMessage());
    }

    return json;
}

From source file:cn.wochu.wh.net.OkHttpClientManager.java

License:Apache License

@SuppressWarnings("static-access")
private Request buildPostRequest(String url, Param[] params) {
    if (params == null) {
        params = new Param[0];
    }/*from ww w  .j  a v  a 2s  . c  o  m*/
    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (Param param : params) {
        builder.add(param.key, param.value);
    }
    RequestBody requestBody = builder.build().create(MediaType.parse("application/json; charset=utf-8"),
            "json");
    return new Request.Builder().url(url).post(requestBody).build();
}

From source file:cn.wochu.wh.net.OkHttpClientManager.java

License:Apache License

private Request buildPostRequest(String url, Param[] params, String content) {
    if (params == null) {
        params = new Param[0];
    }/*from   www .  j a v  a2s  . c o  m*/
    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (Param param : params) {
        builder.add(param.key, param.value);
    }
    RequestBody requestBody = builder.build().create(MediaType.parse("application/json; charset=utf-8"),
            content);
    return new Request.Builder().url(url).post(requestBody).build();
}

From source file:com.ae.apps.pnrstatus.service.NetworkService.java

License:Open Source License

public String doPostRequest(final String targetUrl, final Map<String, String> headers,
        final Map<String, String> params) throws StatusException {
    //RequestBody requestBody = RequestBody.create(WEB_FORM, "");
    try {/* w w  w .  j a  va 2s. c om*/
        Request.Builder requestBuilder = new Request.Builder().url(targetUrl);
        if (null != headers) {
            for (String key : headers.keySet()) {
                requestBuilder.addHeader(key, String.valueOf(headers.get(key)));
            }
        }
        //--
        FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
        if (null != params) {
            for (String key : params.keySet()) {
                formEncodingBuilder.add(key, String.valueOf(params.get(key)));
            }
        }

        RequestBody formBody = formEncodingBuilder.build();
        Request request = requestBuilder.url(targetUrl).post(formBody).build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    } catch (IOException ex) {
        throw new StatusException(ex.getMessage(), StatusException.ErrorCodes.URL_ERROR);
    }
}

From source file:com.appstarter.utils.WebUtils.java

License:Apache License

public static String doHttpPost(String url, List<NameValuePair> params) throws AppStarterException {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "doHttpPost - url: " + debugRequest(url, params));
    }/* w w  w. j  av a2  s . c  o  m*/

    String ret = "";

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout

    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (NameValuePair nvp : params) {
        builder.add(nvp.getName(), nvp.getValue());
    }
    RequestBody formBody = builder.build();

    try {
        Request request = new Request.Builder().url(new URL(url))
                //               .header("User-Agent", "OkHttp Headers.java")
                //               .addHeader("Accept", "application/json; q=0.5")
                .post(formBody).build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            String debugMessage = "doHttpPost - OkHttp.Response is not successful - " + response.message()
                    + " (" + response.code() + ")";
            throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage);
        }
        ret = response.body().string();
    } catch (IOException e) {
        throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET);
    }

    return ret;
}

From source file:com.gqp.duoduo.ui.activity.SearchGoodsForCheckActivity.java

private void getGoodsList(String input) {
    if (TextUtils.isEmpty(input)) {
        return;/*  ww  w.  ja  va  2s.  c  om*/
    }
    showLoading("...");

    FormEncodingBuilder builder = new FormEncodingBuilder().add("page", "0").add("size", "65535");
    if (!TextUtils.isEmpty(isBarcode)) {
        builder.add("barcode", input);
        builder.add("goodsname", "");
    } else {
        builder.add("goodsname", input);
    }
    Request request = new Request.Builder().url(HttpUrl.QUERY_GOODS).post(builder.build())
            .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID()))
            .tag(System.currentTimeMillis()).build();

    compositeSubscription
            .add(HttpRequest.modelRequest(request, GoodsList.class).subscribe(new Subscriber<GoodsList>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    //                                showToast("");
                    dismissLoading();
                    if (e instanceof ErrorMessageException) {
                        if (App.getNetState()) {
                            reLogin();
                        } else {
                            showToast("??");
                        }
                    }
                    showToast(e.getMessage());
                }

                @Override
                public void onNext(GoodsList inventoryList) {
                    dismissLoading();
                    mList.clear();
                    int size = inventoryList.getRows().size();
                    search_result_listview.removeAllViews();
                    mList.addAll(inventoryList.getRows());

                    if (mList != null && mList.size() > 0) {
                        LayoutInflater inflater = LayoutInflater.from(SearchGoodsForCheckActivity.this);
                        int index = 0;
                        for (Goods entity : mList) {
                            View view = inflater.inflate(R.layout.search_goods_for_check_item, null);
                            SearchGoodsViewItemHolder holder = new SearchGoodsViewItemHolder(view);
                            holder.bind(entity, index);
                            search_result_listview.addView(view);

                            View divider = new View(SearchGoodsForCheckActivity.this);
                            divider.setLayoutParams(
                                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
                            divider.setBackgroundColor(Color.parseColor("#dddddd"));
                            search_result_listview.addView(divider);

                            index++;
                        }

                    }
                }
            }));
}

From source file:com.gqp.duoduo.ui.activity.SearchHisOrderActivity.java

private void getInventoryList(String input) {

    if (TextUtils.isEmpty(input)) {
        return;//from w ww.j a  va 2  s .  com
    }
    //        try {
    //            SimpleDateFormat sf = new_version SimpleDateFormat("yyyyMMdd");
    //            Date date = sf.parse(input);
    //            SimpleDateFormat sf1 = new_version SimpleDateFormat("yyyy-MM-dd");
    //            input = sf1.format(date);
    //        }catch (Exception e){
    //            e.printStackTrace();
    //        }

    FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder().add("page", "0").add("size", "100");
    formEncodingBuilder.add("status", "4");
    formEncodingBuilder.add("customer", input);
    Request request = new Request.Builder().url(HttpUrl.ORDER_LIST_NEW).post(formEncodingBuilder.build())
            .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID()))
            .tag(System.currentTimeMillis()).build();

    compositeSubscription
            .add(HttpRequest.modelRequest(request, OrderList.class).subscribe(new Subscriber<OrderList>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    if (e instanceof ErrorMessageException) {
                        if (App.getNetState()) {
                            reLogin();
                        } else {
                            showToast("??");
                        }
                    }
                    //                                showToast(e.getMessage());
                }

                @Override
                public void onNext(OrderList inventoryList) {
                    int size = inventoryList.getRows().get(0).getPageList().size();
                    mList.clear();
                    mList.addAll(inventoryList.getRows().get(0).getPageList());
                    adapter.notifyDataSetChanged();

                }
            }));
}

From source file:com.gqp.duoduo.ui.activity.SearchProductActivity.java

private void getGoodsList(String input) {

    if (TextUtils.isEmpty(input)) {
        return;/*ww w .  j a  va2s .co m*/
    }
    FormEncodingBuilder builder = new FormEncodingBuilder().add("customerid", id).add("page", "0").add("size",
            "65535");
    if (!TextUtils.isEmpty(isBarcode)) {
        builder.add("barcode", input);
        builder.add("goodsname", "");
    } else {
        builder.add("goodsname", input);
    }
    Request request = new Request.Builder().url(HttpUrl.QUERY_GOODS).post(builder.build())
            .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID()))
            .tag(System.currentTimeMillis()).build();

    compositeSubscription
            .add(HttpRequest.modelRequest(request, GoodsList.class).subscribe(new Subscriber<GoodsList>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    //                                showToast("");
                    if (e instanceof ErrorMessageException) {
                        if (App.getNetState()) {
                            reLogin();
                        } else {
                            showToast("??");
                        }
                    }
                    showToast(e.getMessage());
                }

                @Override
                public void onNext(GoodsList inventoryList) {
                    mList.clear();
                    mList.addAll(inventoryList.getRows());
                    listView.removeAllViews();
                    if (mList != null && mList.size() > 0) {
                        LayoutInflater inflater = LayoutInflater.from(SearchProductActivity.this);
                        int index = 0;
                        for (Goods entity : mList) {
                            View view = inflater.inflate(R.layout.search_goods_view_item, null);
                            SearchGoodsViewItemHolder holder = new SearchGoodsViewItemHolder(view);
                            holder.bind(entity, index);
                            listView.addView(view);

                            View divider = new View(SearchProductActivity.this);
                            divider.setLayoutParams(
                                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
                            divider.setBackgroundColor(Color.parseColor("#dddddd"));
                            listView.addView(divider);

                            index++;
                        }

                    }
                }
            }));
}