Example usage for com.squareup.okhttp OkHttpClient newCall

List of usage examples for com.squareup.okhttp OkHttpClient newCall

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient newCall.

Prototype

public Call newCall(Request request) 

Source Link

Document

Prepares the request to be executed at some point in the future.

Usage

From source file:com.navercorp.pinpoint.plugin.okhttp.OkHttpClientBackwardCompatibilityIT.java

License:Apache License

@Test
public void execute() throws Exception {
    Request request = new Request.Builder().url("http://google.com").build();
    OkHttpClient client = new OkHttpClient();
    Response response = client.newCall(request).execute();

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();/*w w  w  .  j  a v a 2 s. c  om*/

    Method callMethod = Call.class.getDeclaredMethod("execute");
    verifier.verifyTrace(Expectations.event("OK_HTTP_CLIENT_INTERNAL", callMethod));
}

From source file:com.nguyenmp.gauchospace.GauchoSpaceClient.java

License:Open Source License

/**
 * Retrieves the details of a user// w ww .  j  av  a2s . c o  m
 * @param url the url of the user page
 * @param session the session of the logged in user to act as
 * @return a User object containing the scraped data
 * @throws IOException in case of a problem or the connection was aborted
  * @throws XMLException XML could not be parsed
 */
public static User getUserProfile(String url, Session session) throws IOException, XMLException {
    //Create http client and context from cookies
    OkHttpClient client = getClient(session);
    Request get = new Request.Builder().url(url).build();

    Response response = client.newCall(get).execute();
    String contentString = response.body().string();

    //Process html string to User object
    return UserParser.getUserFromHtml(contentString);
}

From source file:com.nguyenmp.gauchospace.GauchoSpaceClient.java

License:Open Source License

public static List<User> getParticipantsFromCourse(int courseId, Session session)
        throws IOException, XMLException {
    //Create client and context
    OkHttpClient client = getClient(session);

    //Create GET request
    //We need parameter mode to be 0 for "less detailed" in case default is more detailed
    //We need param perpage to be 50000 to get all participants (this is how the website does it)
    Request get = new Request.Builder()
            .url("https://gauchospace.ucsb.edu/courses/user/index.php?id=" + courseId + "&mode=0&perpage=50000")
            .build();/*from ww  w. j  a v a2  s .c om*/
    String participantsHtmlString = client.newCall(get).execute().body().string();

    return ParticipantsParser.getParticipantsFromHtml(participantsHtmlString);
}

From source file:com.nguyenmp.gauchospace.GauchoSpaceClient.java

License:Open Source License

public static GradeFolder getGrade(int courseId, Session session) throws IOException, XMLException {
    //Create client and context
    OkHttpClient client = getClient(session);

    Request get = new Request.Builder()
            .url("https://gauchospace.ucsb.edu/courses/grade/report/user/index.php?id=" + courseId).build();
    String courseHtml = client.newCall(get).execute().body().string();

    //Compile and parse courses
    return GradeParser.getGradeFromHtml(courseHtml);
}

From source file:com.nguyenmp.gauchospace.GauchoSpaceClient.java

License:Open Source License

/**
 * Gets a list of forums that belong under the specified course.
 * @param courseID The ID of the course under which these forums belong.
  * @param session the session of the logged in user to act as
 * @return A list of Forums that belong to this Course.  Null if it 
 * couldn't be parsed. //from   w  w w .jav  a 2 s.  c o m
 * @throws IOException
 */
public static List<Forum> getForums(int courseID, Session session) throws IOException, XMLException {
    //Create client and context
    OkHttpClient client = getClient(session);
    Request get = new Request.Builder()
            .url("https://gauchospace.ucsb.edu/courses/mod/forum/index.php?id=" + courseID).build();

    String forumsHtml = client.newCall(get).execute().body().string();

    return ForumsParser.getForums(forumsHtml);
}

From source file:com.nguyenmp.gauchospace.GauchoSpaceClient.java

License:Open Source License

/**
 * Gets a list of forums that belong under the specified course.
 * @param forumID The ID of the forum to fetch the discussions from
  * @param session the session of the logged in user to act as
 * @return A list of Forums that belong to this Course.
 * @throws IOException//  ww  w  .  j av a 2s . co m
 */
public static List<Discussion> getDiscussions(int forumID, Session session) throws IOException, XMLException {
    //Create client and context
    OkHttpClient client = getClient(session);

    Request get = new Request.Builder()
            .url("https://gauchospace.ucsb.edu/courses/mod/forum/view.php?f=" + forumID).build();
    String forumHtml = client.newCall(get).execute().body().string();

    return ForumParser.getDiscussions(forumHtml);
}

From source file:com.nuvolect.securesuite.webserver.Comm.java

License:Open Source License

/**
 * Send a post message./*w  w w .  j  a  v  a2s  .c  o m*/
 * @param url
 * @param params
 * @param listener
 */
public static void sendPost(String url, final Map<String, String> params, CommPostCallbacks listener) {

    String postBody = "";
    String amphersand = "";

    OkHttpClient okHttpClient = WebService.getOkHttpClient();

    for (Map.Entry<String, String> entry : params.entrySet()) {

        postBody += amphersand;
        postBody += entry.getKey();
        postBody += "=";
        postBody += entry.getValue();
        amphersand = "&";
    }

    Request request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
            .header(CConst.SEC_TOK, CrypServer.getSecTok()).build();

    try {
        com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute();

        if (listener != null && response.isSuccessful()) {

            listener.success(response.body().string());
        } else {

            if (listener != null)
                listener.fail("Unexpected code " + response);
        }
        ;

        /**
         * Causes exception, can only read the response body 1 time
         * https://github.com/square/okhttp/issues/1240
         */
        //            LogUtil.log(LogUtil.LogType.REST, response.body().string());

    } catch (IOException e) {
        listener.fail("IOException: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
}

From source file:com.nuvolect.securesuite.webserver.Comm.java

License:Open Source License

public static void sendPostUi(final Context ctx, String url, final Map<String, String> params,
        final CommPostCallbacks cb) {

    String postBody = "";
    String amphersand = "";

    OkHttpClient okHttpClient = WebService.getOkHttpClient();

    for (Map.Entry<String, String> entry : params.entrySet()) {

        postBody += amphersand;/*from  w w  w  .ja  v a2s  . c  o  m*/
        postBody += entry.getKey();
        postBody += "=";
        postBody += entry.getValue();
        amphersand = "&";
    }

    Request request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
            .header(CConst.SEC_TOK, CrypServer.getSecTok()).build();

    okHttpClient.newCall(request).enqueue(new Callback() {

        Handler mainHandler = new Handler(ctx.getMainLooper());

        @Override
        public void onFailure(Request request, IOException e) {

            LogUtil.log("okHttpClient.netCall.onFailure");
            LogUtil.logException(LogUtil.LogType.REST, e);
        }

        @Override
        public void onResponse(Response response) throws IOException {

            final String responseStr;
            final boolean success = response.isSuccessful();

            if (success)
                responseStr = response.body().string();
            else
                responseStr = response.message();

            mainHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (!success) {
                        if (cb != null)
                            cb.fail("unexpected code " + responseStr);
                        return;
                    }
                    if (cb != null)
                        cb.success(responseStr);

                }
            });

        }
    });
}

From source file:com.onaio.steps.helper.UploadFileTask.java

License:Apache License

@Override
protected Boolean doInBackground(File... files) {
    if (!TextUtils.isEmpty(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL))) {
        try {/*from   ww  w  .  j  a v  a2 s .  c om*/
            OkHttpClient client = new OkHttpClient();

            final MediaType MEDIA_TYPE = MediaType.parse("text/csv");

            RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                    .addFormDataPart("file", files[0].getName(), RequestBody.create(MEDIA_TYPE, files[0]))
                    .build();

            Request request = new Request.Builder()
                    .url(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL)).post(requestBody)
                    .build();
            client.newCall(request).execute();
            new CustomNotification().notify(activity, R.string.export_complete,
                    R.string.export_complete_message);
            return true;
        } catch (IOException e) {
            new Logger().log(e, "Export failed.");
            new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
        }
    } else {
        new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
    }

    return false;
}

From source file:com.peach.masktime.module.net.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    LogUtils.i(TAG, "timeoutMs = " + timeoutMs);
    client.setProxy(Proxy.NO_PROXY);
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//w  w  w.j av a  2 s.  c  om
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }
    return response;
}