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: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());
    }/*from   w w  w. j a  v a  2s.co  m*/

    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();
}

From source file:uk.co.craiggarrigan.dvsacancellationfinder.CancellationService.java

public String[] getCancellations(final String licenseNumber, final String applicationRefNumber) {

    Log.d(SVC, "Getting cancellations");

    AsyncTask<Void, Void, List<String>> task = new AsyncTask<Void, Void, List<String>>() {
        @Override//www.j  a v a2  s  .com
        protected List<String> doInBackground(Void... params) {

            List<String> result = new ArrayList<>();

            try {

                RequestBody formBody = new FormEncodingBuilder().add("javascriptEnabled", "true")
                        .add("passwordType", "NORMAL").add("username", licenseNumber)
                        .add("password", applicationRefNumber).add("alternativePassword", "")
                        .add("booking-login", "Continue").build();
                Request request = new Request.Builder().url("https://driverpracticaltest.direct.gov.uk/login")
                        .post(formBody).build();

                Log.d(SVC, "Sending HTTP request");

                Response response = client.newCall(request).execute();

                Log.d(SVC, "Extracting CSRF token");

                BufferedReader r = new BufferedReader(new InputStreamReader(response.body().byteStream()));
                String s;
                String csrf = null;
                while ((s = r.readLine()) != null) {
                    Log.d(SVC, s);
                    Matcher m = Pattern.compile("csrftoken=([a-zA-Z0-9]{32})").matcher(s);
                    if (m.find()) {
                        csrf = m.group(1);
                        //break;
                    }
                }

                Log.d(SVC, "CSRF token = " + csrf);

                request = new Request.Builder().url(
                        "https://driverpracticaltest.direct.gov.uk/manage?execution=e1s1&_eventId=editTestDateTime&csrftoken="
                                + csrf)
                        .build();

                response = client.newCall(request).execute();

                printResponse(response);

                formBody = new FormEncodingBuilder().add("testChoice", "ASAP").add("preferredTestDate", "")
                        .addEncoded("drivingLicenceSubmit", "Find+available+dates").build();

                request = new Request.Builder().url(
                        "https://driverpracticaltest.direct.gov.uk/manage?execution=e1s2&_eventId=proceed&csrftoken="
                                + csrf)
                        .post(formBody).build();

                response = client.newCall(request).execute();

                printResponse(response);

                request = new Request.Builder()
                        .url("https://driverpracticaltest.direct.gov.uk/manage?execution=e1s3").build();

                response = client.newCall(request).execute();

                r = new BufferedReader(new InputStreamReader(response.body().byteStream()));
                List<String> slots = new ArrayList<>();
                while ((s = r.readLine()) != null) {
                    Log.d(SVC, s);
                    Matcher m = Pattern.compile("chosenSlot=([0-9]{13})").matcher(s);
                    if (m.find()) {
                        String strTimestamp = m.group(1);
                        Date d = new Date(Long.parseLong(strTimestamp));
                        slots.add(DateFormat.getDateTimeInstance().format(d));
                    }
                }

                result = slots;

            } catch (IOException e) {
                Log.i(SVC, "Failed HTTP", e);
            }

            return result;
        }
    };

    List<String> result = new ArrayList<>();
    result.add("Failed");
    try {
        Log.d(SVC, "Starting task");
        result = task.execute().get();
    } catch (InterruptedException | ExecutionException e) {
        Log.i(SVC, "Failed task", e);
    }

    return result.toArray(new String[result.size()]);
}

From source file:zblibrary.demo.manager.HttpRequest.java

License:Apache License

/**
 * @param paramList/*from  w  w w.  j  a va 2  s  .co  m*/
 *            ??
 * @param url
 *            ?url
 * @param requestCode
 *            ?onActivityResult??activity??<br/>
 *             ???
 *            {@link OnHttpResponseListener#onHttpRequestError(int, Exception)}
 *             <br/>
 *            {@link OnHttpResponseListener#onHttpRequestError(int, Exception)}
 * <br/>
 *            activity?requestCode??serverResultCode???
 *            json?json? 
 *
 * @param listener
 */
private void httpPost(final List<Parameter> paramList, final String url, final int requestCode,
        final OnHttpResponseListener listener) {

    new AsyncTask<Void, Void, Exception>() {

        int resultCode;
        String resultData;

        @Override
        protected Exception doInBackground(Void... params) {
            OkHttpClient client = getHttpClient(url);
            if (client == null) {
                return new Exception("httpPost  AsyncTask.doInBackground  client == null >> return;");
            }

            FormEncodingBuilder fBuilder = new FormEncodingBuilder();
            if (paramList != null) {
                for (Parameter p : paramList) {
                    fBuilder.add(p.key, p.value);
                }
            }

            JSONObject jsonObject = null;
            try {
                jsonObject = getResponseObject(client,
                        new Request.Builder().addHeader("token", getToken(paramList))
                                .url(StringUtil.getNoBlankString(url)).post(fBuilder.build()).build());
            } catch (Exception e) {
                Log.e(TAG, "httpPost  AsyncTask.doInBackground  try {  jsonObject = getResponseObject(..."
                        + "} catch (Exception e) {\n" + e.getMessage());
                return e;
            }

            resultCode = getResponseCode(jsonObject);
            resultData = getResponseData(jsonObject);

            return null;
        }

        @Override
        protected void onPostExecute(Exception exception) {
            super.onPostExecute(exception);
            httpPostExecute(listener, requestCode, exception, resultCode, resultData);
        }

    }.execute();
}

From source file:zuo.biao.library.manager.HttpManager.java

License:Apache License

/**POST
 * @param paramList ??/*  ww w  . jav a 2 s.com*/
 * @param url ?url
 * @param requestCode
 *            ?onActivityResult??activity?????
 *            {@link OnHttpResponseListener#onHttpResponse(int, String, Exception)}<br>  
 *            ??requestCode??
 * @param listener
 */
public void post(final List<Parameter> paramList, final String url, final int requestCode,
        final OnHttpResponseListener listener) {

    new AsyncTask<Void, Void, Exception>() {

        String result;

        @Override
        protected Exception doInBackground(Void... params) {
            OkHttpClient client = getHttpClient(url);
            if (client == null) {
                return new Exception(TAG + ".post  AsyncTask.doInBackground  client == null >> return;");
            }

            FormEncodingBuilder fBuilder = new FormEncodingBuilder();
            if (paramList != null) {
                for (Parameter p : paramList) {
                    fBuilder.add(StringUtil.getTrimedString(p.key), StringUtil.getTrimedString(p.value));
                }
            }

            try {
                result = getResponseJson(client, new Request.Builder().addHeader(KEY_TOKEN, getToken(url))
                        .url(StringUtil.getNoBlankString(url)).post(fBuilder.build()).build());
                // result = "{\"code\":102}";
            } catch (Exception e) {
                Log.e(TAG, "post  AsyncTask.doInBackground  try {  result = getResponseJson(..."
                        + "} catch (Exception e) {\n" + e.getMessage());
                return e;
            }

            return null;
        }

        @Override
        protected void onPostExecute(Exception exception) {
            super.onPostExecute(exception);
            listener.onHttpResponse(requestCode, result, exception);
        }

    }.execute();
}