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:org.addhen.smssync.net.MessageSyncHttpClient.java

License:Open Source License

/**
 * Get HTTP Entity populated with data in a format specified by the current sync scheme
 *//*from   w w w  .  ja  va 2s .  c  om*/
private void setHttpEntity(SyncDataFormat format) throws Exception {
    RequestBody body;
    switch (format) {
    case JSON:
        body = RequestBody.create(JSON, DataFormatUtil.makeJSONString(getParams()));
        log("setHttpEntity format JSON");
        Util.logActivities(context, "setHttpEntity format JSON");
        break;
    case XML:
        //TODO: Make parent node URL specific as well
        body = RequestBody.create(XML, DataFormatUtil.makeXMLString(getParams(), "payload", HTTP.UTF_8));
        log("setHttpEntity format XML");
        Util.logActivities(context, context.getString(R.string.http_entity_format, "XML"));
        break;
    case YAML:
        body = RequestBody.create(YAML, DataFormatUtil.makeYAMLString(getParams()));
        log("setHttpEntity format YAML");
        Util.logActivities(context, context.getString(R.string.http_entity_format, "YAML"));
        break;
    case URLEncoded:
        log("setHttpEntity format URLEncoded");
        FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
        List<NameValuePair> params = getParams();
        for (NameValuePair pair : params) {
            formEncodingBuilder.add(pair.getName(), pair.getValue());
        }
        Util.logActivities(context, context.getString(R.string.http_entity_format, "URLEncoded"));
        body = formEncodingBuilder.build();
        break;
    default:
        Util.logActivities(context, context.getString(R.string.invalid_data_format));
        throw new Exception("Invalid data format");
    }

    setRequestBody(body);

}

From source file:org.catrobat.catroid.web.ServerCalls.java

License:Open Source License

public String httpFormUpload(String url, Map<String, String> postValues) throws WebconnectionException {
    FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();

    if (postValues != null) {
        for (Map.Entry<String, String> entry : postValues.entrySet()) {
            formEncodingBuilder.add(entry.getKey(), entry.getValue());
        }/*from w  w w. j a v a  2 s.  c  o m*/
    }

    Request request = new Request.Builder().url(url).post(formEncodingBuilder.build()).build();

    try {
        Response response = okHttpClient.newCall(request).execute();
        return response.body().string();
    } catch (IOException ioException) {
        Log.e(TAG, Log.getStackTraceString(ioException));
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK,
                "Connection could not be established!");
    }
}

From source file:org.floens.chan.core.http.DeleteHttpCall.java

License:Open Source License

@Override
public void setup(Request.Builder requestBuilder) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder();
    formBuilder.add(Integer.toString(reply.no), "delete");
    if (onlyImageDelete) {
        formBuilder.add("onlyimgdel", "on");
    }//  w w  w .j a v a 2s  . c o m
    formBuilder.add("mode", "usrdel");
    formBuilder.add("pwd", reply.password);

    requestBuilder.url(ChanUrls.getDeleteUrl(reply.board));
    requestBuilder.post(formBuilder.build());
}

From source file:org.floens.chan.core.http.PassHttpCall.java

License:Open Source License

@Override
public void setup(Request.Builder requestBuilder) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder();

    formBuilder.add("act", "do_login");

    formBuilder.add("id", token);
    formBuilder.add("pin", pin);

    requestBuilder.url(ChanUrls.getPassUrl());
    requestBuilder.post(formBuilder.build());
}

From source file:org.floens.chan.core.manager.ReplyManager.java

License:Open Source License

public void postPass(String token, String pin, final PassListener passListener) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder();

    formBuilder.add("act", "do_login");

    formBuilder.add("id", token);
    formBuilder.add("pin", pin);

    Request.Builder request = new Request.Builder().url(ChanUrls.getPassUrl()).post(formBuilder.build());

    makeOkHttpCall(request, new Callback() {
        @Override//w w w .  jav  a 2 s  .  c  om
        public void onFailure(Request request, IOException e) {
            final PassResponse res = new PassResponse();
            res.isError = true;
            res.message = context.getString(R.string.pass_error);
            runUI(new Runnable() {
                public void run() {
                    passListener.onResponse(res);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                onFailure(response.request(), null);
                return;
            }
            String responseString = response.body().string();
            response.body().close();

            final PassResponse res = new PassResponse();
            if (responseString.contains("Your device is now authorized")) {
                List<String> cookies = response.headers("Set-Cookie");
                String passId = null;
                for (String cookie : cookies) {
                    try {
                        List<HttpCookie> parsedList = HttpCookie.parse(cookie);
                        for (HttpCookie parsed : parsedList) {
                            if (parsed.getName().equals("pass_id") && !parsed.getValue().equals("0")) {
                                passId = parsed.getValue();
                            }
                        }
                    } catch (IllegalArgumentException ignored) {
                    }
                }
                if (passId != null) {
                    res.passId = passId;
                    res.message = "Success! Your device is now authorized.";
                } else {
                    res.isError = true;
                    res.message = "Could not get pass id";
                }
            } else {
                res.isError = true;
                if (responseString.contains("Your Token must be exactly 10 characters")) {
                    res.message = "Incorrect token";
                } else if (responseString.contains("You have left one or more fields blank")) {
                    res.message = "You have left one or more fields blank";
                } else if (responseString.contains("Incorrect Token or PIN")) {
                    res.message = "Incorrect Token or PIN";
                } else {
                    res.unknownError = true;
                }
            }

            runUI(new Runnable() {
                public void run() {
                    passListener.onResponse(res);
                }
            });
        }
    });
}

From source file:org.floens.chan.core.manager.ReplyManager.java

License:Open Source License

public void postDelete(final SavedReply reply, boolean onlyImageDelete, final DeleteListener listener) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder();
    formBuilder.add(Integer.toString(reply.no), "delete");
    if (onlyImageDelete) {
        formBuilder.add("onlyimgdel", "on");
    }//  w w  w .  j av  a2s  .  c  o  m
    formBuilder.add("mode", "usrdel");
    formBuilder.add("pwd", reply.password);

    Request.Builder request = new Request.Builder().url(ChanUrls.getDeleteUrl(reply.board))
            .post(formBuilder.build());

    makeOkHttpCall(request, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            final DeleteResponse res = new DeleteResponse();
            res.isNetworkError = true;
            runUI(new Runnable() {
                @Override
                public void run() {
                    listener.onResponse(res);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                onFailure(response.request(), null);
                return;
            }
            String responseString = response.body().string();
            response.body().close();

            final DeleteResponse res = new DeleteResponse();
            res.responseData = responseString;

            if (responseString.contains("You must wait longer before deleting this post")) {
                res.isUserError = true;
                res.isTooSoonError = true;
            } else if (responseString.contains("Password incorrect")) {
                res.isUserError = true;
                res.isInvalidPassword = true;
            } else if (responseString.contains("You cannot delete a post this old")) {
                res.isUserError = true;
                res.isTooOldError = true;
            } else if (responseString.contains("Updating index")) {
                res.isSuccessful = true;
            }

            runUI(new Runnable() {
                @Override
                public void run() {
                    listener.onResponse(res);
                }
            });
        }
    });
}

From source file:pw.isdust.isdust.Http.java

License:Open Source License

public String post_string(String url, String postbody) throws IOException {
    //POST//w  ww.  j a v  a 2  s  . co  m
    String mstring_fenge1[] = postbody.split("&");

    FormEncodingBuilder mFormEncodingBuilder = new FormEncodingBuilder();
    Request.Builder a = new Request.Builder();

    RequestBody mformBody;

    for (int i = 0; i < mstring_fenge1.length; i++) {
        String mstring_fenge2[] = mstring_fenge1[i].split("=");
        if (mstring_fenge2.length == 2) {
            mFormEncodingBuilder.add(mstring_fenge2[0], mstring_fenge2[1]);
        }
        if (mstring_fenge2.length == 1) {
            mFormEncodingBuilder.add(mstring_fenge1[i].replace("=", ""), "");
        }
    }
    mformBody = mFormEncodingBuilder.build();
    //String b=mformBody.toString();
    //POST
    System.out.println(mformBody.toString());

    //??
    Request request = new Request.Builder().url(url).post(mformBody).header("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36")
            .build();

    Response response_1;
    response_1 = mHTTP.newCall(request).execute();
    return response_1.body().string();

}

From source file:studio.imedia.vehicleinspection.activity.PersonalInfoActivity.java

/**
 * ?//from   w  w w.j av a2 s.  c om
 *
 * @param urlSB
 * @param avatarPath
 */
private void uploadInfo(StringBuffer urlSB, String avatarPath) {
    Log.d("submit", "url " + urlSB.toString());
    String url = urlSB.toString();
    int id = (int) SPUtil.get(mContext, Constant.Key.USER_ID, Constant.Type.INTEGER);
    mUsername = tvUsername.getText().toString().trim();
    String gender = tvGender.getText().toString();
    if (gender.equals(""))
        mGender = MALE;
    else
        mGender = FEMALE;
    mSignature = etSignature.getText().toString().trim();

    // ?
    FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
    formEncodingBuilder.add("id", String.valueOf(id)).add("name", mUsername)
            .add("gender", String.valueOf(mGender)).add("signature", mSignature);
    if (isAvatarUpdate && avatarPath != null)
        formEncodingBuilder.add("avatar", avatarPath);

    RequestBody formBody = formEncodingBuilder.build();

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

    mClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            Toast.makeText(mContext, "??", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful())
                throw new IOException("Unexpected code " + response);

            String jsonStr = response.body().string();
            Log.d("submit", "json " + jsonStr);
            try {
                int status = new JSONObject(jsonStr).getInt("status");
                if (status == 0)
                    mHandler.sendEmptyMessage(MSG_UPLOAD_INFO_SUCCESS);
                else
                    mHandler.sendEmptyMessage(MSG_UPLOAD_INFO_FAIL);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:studio.imedia.vehicleinspection.fragments.CarInfoFragment.java

/**
 * ?//  w w w.  j a  v a2s  .c  o  m
 */
private void uploadCarInfo(StringBuffer urlSB, String picPath) {
    String url = urlSB.toString();
    // ??
    mLicensePicPath = picPath;
    mDetailedAddress = tvCity.getText().toString().trim();
    mEngineNum = etEngineNum.getText().toString().trim();
    mRegisterTime = tvRegisterDate.getText().toString().trim();

    // ?...
    FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder().add("id", String.valueOf(mId))
            .add("carBrandId", String.valueOf(mCarBrandId)).add("carTypeId", String.valueOf(mCarTypeId))
            .add("engineNum", mEngineNum).add("registerTime", mRegisterTime)
            .add("provinId", String.valueOf(mProvinceId)) // ?id
            .add("cityId", String.valueOf(mCityId)).add("countyId", String.valueOf(mCountyId))
            .add("detailedAddress", mDetailedAddress);
    if (isLicenseUpdate && picPath != null)
        formEncodingBuilder.add("licensePic", mLicensePicPath);

    RequestBody formBody = formEncodingBuilder.build();

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

    mClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            mHandler.sendEmptyMessage(CONNECT_FAIL);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful())
                throw new IOException("Unexpected code " + response);

            String jsonStr = response.body().string();
            try {
                int status = new JSONObject(jsonStr).getInt("status");
                if (status == 0) {
                    mHandler.sendEmptyMessage(MSG_UP_INFO_SUCCESS);
                } else {
                    mHandler.sendEmptyMessage(MSG_UP_INFO_FAIL);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:tk.breezy64.pantex.core.Util.java

public static String post(String url, Map<String, String> params) throws IOException {
    OkHttpClient client = getClient(DEFAULT_SESSION);
    FormEncodingBuilder b = new FormEncodingBuilder();
    for (Map.Entry<String, String> e : params.entrySet()) {
        b.add(e.getKey(), e.getValue());
    }//  w ww.j  a  v  a2  s  . c om

    Request req = new Request.Builder().post(b.build()).url(url).build();

    Response r = client.newCall(req).execute();
    System.out.println("Result: " + r.toString());
    return r.body().string();
}