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:com.gqp.duoduo.ui.activity.SearchProductForOrderActivity.java

private void getGoodsList(String input) {

    if (TextUtils.isEmpty(input)) {
        return;/*from www . j av a2 s.  com*/
    }
    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(SearchProductForOrderActivity.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(SearchProductForOrderActivity.this);
                            divider.setLayoutParams(
                                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
                            divider.setBackgroundColor(Color.parseColor("#dddddd"));
                            listView.addView(divider);

                            index++;
                        }

                    }
                }
            }));
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java

License:Apache License

/**
 * Send this resource request asynchronously, with the given form parameters as the request body.
 * This method will set the content type header to "application/x-www-form-urlencoded".
 *
 * @param formParameters The parameters to put in the request body
 * @param listener       The listener whose onSuccess or onFailure methods will be called when this request finishes.
 *///from   www  .  j  a  v  a 2s .  c  o m
protected void send(Map<String, String> formParameters, ResponseListener listener) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder();

    for (Map.Entry<String, String> param : formParameters.entrySet()) {
        formBuilder.add(param.getKey(), param.getValue());
    }

    RequestBody body = formBuilder.build();

    sendRequest(listener, body);
}

From source file:com.ibm.watson.developer_cloud.http.RequestBuilder.java

License:Open Source License

/**
 * Builds a request with the given set of parameters and files.
 * /*www .ja va  2s .  c  o  m*/
 * 
 * @return HTTP request, prepared to be executed
 */
public Request build() {
    final Builder builder = new Request.Builder();
    // URL
    builder.url(toUrl());

    // POST/PUT require a body so send an empty body if the actual is null
    RequestBody requestBody = body;
    if (body == null)
        requestBody = RequestBody.create(null, new byte[0]);

    if (!formParams.isEmpty()) {
        final FormEncodingBuilder formBody = new FormEncodingBuilder();
        for (final NameValue param : formParams) {
            final String value = param.getValue() != null ? param.getValue() : "";
            formBody.add(param.getName(), value);
        }
        requestBody = formBody.build();
    }

    // accept application/json by default
    builder.addHeader(HttpHeaders.ACCEPT, HttpMediaType.APPLICATION_JSON);

    if (!headers.isEmpty()) {
        for (final NameValue header : headers) {
            builder.addHeader(header.getName(), header.getValue());
        }
    }

    switch (method) {
    case GET:
        builder.get();
        break;
    case POST:
        builder.post(requestBody);
        break;
    case PUT:
        builder.put(requestBody);
        break;
    case DELETE:
        builder.delete(requestBody);
        break;
    }

    return builder.build();
}

From source file:com.lidroid.xutils.HttpUtils.java

License:Apache License

@NonNull
private RequestBody buildFormRequestBody(RequestParams params) {

    if (params != null) {
        List<NameValuePair> bodyParams = params.getBodyParams();

        if (bodyParams != null) {
            FormEncodingBuilder builder = new FormEncodingBuilder();

            for (NameValuePair param : params.getBodyParams()) {
                builder.add(param.getName(), param.getValue());
            }/* w ww .  j a v a 2s.  c om*/

            return builder.build();
        }

        HttpEntity entity = params.getEntity();
        if (entity != null) {
            try {
                String body = InputStreamToString(entity.getContent(), "utf-8");
                return RequestBody.create(MediaType.parse("application/javascript"), body);
            } catch (Exception ex) {
                LogUtil.e(ex.getMessage());
            }
        }
    }

    return RequestBody.create(MediaType.parse("application/javascript"), "");
}

From source file:com.liuguangqiang.asyncokhttp.RequestParams.java

License:Apache License

public RequestBody toRequestBody() {
    FormEncodingBuilder builder = new FormEncodingBuilder();

    for (HashMap.Entry<String, String> entry : params.entrySet()) {
        builder.add(entry.getKey(), entry.getValue());
    }/*from   w w w  .  java 2  s. co  m*/

    return builder.build();

}

From source file:com.mcxiaoke.next.http.NextRequest.java

License:Apache License

protected RequestBody getRequestBody() throws IOException {
    if (!supportBody()) {
        return null;
    }/*from w ww  .  j ava  2s  .  c  o m*/
    if (body != null) {
        return RequestBody.create(HttpConsts.MEDIA_TYPE_OCTET_STREAM, body);
    }
    RequestBody requestBody;
    if (hasParts()) {
        final MultipartBuilder multipart = new MultipartBuilder();
        for (final BodyPart part : parts()) {
            if (part.getBody() != null) {
                multipart.addFormDataPart(part.getName(), part.getFileName(), part.getBody());
            }
        }
        for (Map.Entry<String, String> entry : form().entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            multipart.addFormDataPart(key, value == null ? "" : value);
        }
        requestBody = multipart.type(MultipartBuilder.FORM).build();
    } else if (hasForms()) {
        final FormEncodingBuilder bodyBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : form().entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            bodyBuilder.add(key, value == null ? "" : value);
        }
        requestBody = bodyBuilder.build();
    } else {
        requestBody = null;
    }
    return requestBody;
}

From source file:com.near.chimerarevo.fragments.CommentsFragment.java

License:Apache License

private void createCommentDialog(final int parent) {
    CustomDialog.Builder builder;/*from   w  ww  .jav  a2s.c  o  m*/

    if (parentId == -1)
        builder = new CustomDialog.Builder(getActivity(), getResources().getString(R.string.text_addcomment),
                getResources().getString(R.string.text_sendcomment));
    else
        builder = new CustomDialog.Builder(getActivity(), getResources().getString(R.string.text_replycomment),
                getResources().getString(R.string.text_sendcomment));

    builder.positiveColorRes(android.R.color.holo_blue_bright);
    builder.titleColorRes(android.R.color.holo_red_light);
    builder.titleAlignment(BaseDialog.Alignment.CENTER);
    builder.negativeText(getResources().getString(R.string.text_cancel));
    builder.negativeColorRes(android.R.color.holo_red_dark);

    final CustomDialog dialog = builder.build();
    dialog.setCustomView(
            LayoutInflater.from(getActivity()).inflate(R.layout.dialog_comment_layout, null, false));
    dialog.setCancelable(false);

    dialog.setClickListener(new CustomDialog.ClickListener() {
        @Override
        public void onConfirmClick() {
            EditText text = (EditText) dialog.findViewById(R.id.comment_edittext);

            isDialogOpen = false;

            if (checkEditText(text, getResources())) {
                SnackbarUtils
                        .showMultiShortSnackbar(getActivity(),
                                getResources().getString(R.string.text_textnotempty), CommentsFragment.this)
                        .dismissOnActionClicked(true).actionLabel(getResources().getString(R.string.text_close))
                        .actionColor(getResources().getColor(android.R.color.holo_red_dark))
                        .show(getActivity());

                return;
            }

            String commentText = text.getText().toString() + "\n\n"
                    + getResources().getString(R.string.text_sentfromapp);

            FormEncodingBuilder feb = new FormEncodingBuilder().add("access_token", access_token)
                    .add("api_key", Constants.DISQUS_API_KEY).add("api_secret", Constants.DISQUS_API_SECRET)
                    .add("message", commentText).add("thread", thread_id);

            if (parent != -1)
                feb.add("parent", String.valueOf(parent));

            Request request = new Request.Builder().url(Constants.DISQUS_POST_COMMENT).post(feb.build())
                    .tag(FRAGMENT_TAG).build();

            if (mDialog == null)
                mDialog = ProgressDialogUtils.getInstance(getActivity(), R.string.text_sending_comment);
            else
                mDialog = ProgressDialogUtils.modifyInstance(mDialog, R.string.text_sending_comment);

            mDialog.show();

            OkHttpUtils.getInstance().newCall(request).enqueue(new PostCommentCallback());
        }

        @Override
        public void onCancelClick() {
            isDialogOpen = false;
            mFab.show();
        }
    });

    isDialogOpen = true;
    mFab.hide();
    dialog.show();
}

From source file:com.sonaive.v2ex.sync.api.Api.java

License:Open Source License

public Bundle sync(HttpMethod httpMethod) {
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = null;//  w w w .j ava2s. c  om

    if (httpMethod == HttpMethod.GET) {
        request = new Request.Builder().url(mUrl).build();
    } else {
        String json = mArguments.getString(ARG_API_PARAMS);
        HashMap params = new Gson().fromJson(json, HashMap.class);
        FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : ((HashMap<String, String>) params).entrySet()) {
            formBodyBuilder.add(entry.getKey(), entry.getValue());
        }
        RequestBody formBody = formBodyBuilder.build();
        request = new Request.Builder().url(mUrl).post(formBody).build();
    }

    try {
        Response response = okHttpClient.newCall(request).execute();
        if (response != null && response.code() == 200) {
            LOGD(TAG, "Request: " + mUrl + ", server returned HTTP_OK, so fetching was successful.");
            mArguments.putString(Api.ARG_RESULT, response.body().string());
            return mArguments;
        } else if (response != null && response.code() == 403) {
            LOGW(TAG, "Request: " + mUrl + ", Server returned 403, fetching was failed.");
        } else {
            LOGW(TAG, "Request: " + mUrl + ", Fetching was failed. Unknown reason");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

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

License:Apache License

private static RequestBody paramsMapToRequestBody(Map<String, String> params) {
    if (params != null) {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : params.entrySet())
            builder.add(entry.getKey(), entry.getValue());
        return builder.build();
    }//from  www. j  a  v a  2  s  . co  m
    return null;
}

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());
    }//from w w w.  ja  v  a 2 s  .  co  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) {

                    }
                }

            }

        }
    });
}