Example usage for com.squareup.okhttp Request.Builder url

List of usage examples for com.squareup.okhttp Request.Builder url

Introduction

In this page you can find the example usage for com.squareup.okhttp Request.Builder url.

Prototype

HttpUrl url

To view the source code for com.squareup.okhttp Request.Builder url.

Click Source Link

Usage

From source file:com.gezhii.fitgroup.network.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();
    int timeoutMs = 30000;
    Log.i("timeoutMs", timeoutMs);
    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  a  v a 2 s  . co m*/
    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;
}

From source file:com.github.leonardoxh.temporeal.app.service.AbstractService.java

License:Apache License

/**
 * Este metodo vai fazer as requisicoes HTTP para nos
 * enviando o modelo se necessario/* w  w w .j  a  v  a2s.c o m*/
 * @param endPoint a URL da requisicao
 * @param model o modelo para enviar note que se este modelo for null iremos fazer um GET
 *              por que temos um padrao no servidor :)
 * @param <T> o tipo do modelo (qualquer um que derive de Model)
 * @return a resposta da URL ou null em caso de falha
 */
protected <T extends Model> Response makeRequest(String endPoint, T model) {
    try {
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(endPoint);
        if (model == null) {
            requestBuilder.get();
        } else {
            requestBuilder.post(RequestBody.create(Constants.JSON_MEDIA_TYPE, JsonUtils.toJson(model)));
        }
        return mClient.newCall(requestBuilder.build()).execute();
    } catch (IOException e) {
        /* Essa exception sera lancada caso uma falha na
         * comunicacao aconteca, entao iremos retornar null */
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.leonardoxh.temporeal.model.listeners.PushSender.java

License:Apache License

public static void send(String entity) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(ApplicationConfiguration.PUSH_SERVICE_URL);
    requestBuilder//ww  w .j a  v a  2 s  . c om
            .post(RequestBody.create(MediaType.parse("application/json"), getJsonOfRegistrationsId(entity)));
    requestBuilder.header("Authorization", ApplicationConfiguration.GCM_PROJECT_ID);
    OkHttpClient okHttp = new OkHttpClient();
    try {
        Response response = okHttp.newCall(requestBuilder.build()).execute();
        System.out.println("Response code: " + response.code());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java

License:Apache License

protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams,
        HttpRequest request, final HttpResponse response) throws IOException {
    try {/*from  w w w  . j  a  va2  s  .c o  m*/
        String urlStr = url.toString();

        if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) {
            urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT)
                    + "/odo";
        }

        // setup okhttp to ignore ssl issues
        OkHttpClient okHttpClient = getUnsafeOkHttpClient();
        okHttpClient.setFollowRedirects(false);
        okHttpClient.setFollowSslRedirects(false);

        Request.Builder okRequestBuilder = new Request.Builder();

        /*
         * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port
         * by checking it only has a : as part of http://
         */
        if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) {
            int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT);
            urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort);
        }

        okRequestBuilder = okRequestBuilder.url(urlStr);

        // copy request headers
        Enumeration<?> enm = request.getFieldNames();
        boolean isGet = "GET".equals(request.getMethod());
        boolean hasContent = false;
        boolean usedContentLength = false;
        long contentLength = 0;
        while (enm.hasMoreElements()) {
            String hdr = (String) enm.nextElement();

            if (!isGet && HttpFields.__ContentType.equals(hdr)) {
                hasContent = true;
            }
            if (!isGet && HttpFields.__ContentLength.equals(hdr)) {
                contentLength = Long.parseLong(request.getField(hdr));
                usedContentLength = true;
            }

            Enumeration<?> vals = request.getFieldValues(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) {
                        hasContent = true;
                    }

                    if (!_DontProxyHeaders.containsKey(hdr)) {
                        okRequestBuilder = okRequestBuilder.addHeader(hdr, val);
                        //httpReq.addRequestHeader(hdr, val);
                    }
                }
            }
        }

        if ("GET".equals(request.getMethod())) {
            // don't need to do anything else
        } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod())
                || "DELETE".equals(request.getMethod())) {
            RequestBody okRequestBody = null;
            if (hasContent) {
                final String contentType = request.getContentType();
                final byte[] bytes = IOUtils.toByteArray(request.getInputStream());

                okRequestBody = new RequestBody() {
                    @Override
                    public MediaType contentType() {
                        MediaType.parse(contentType);
                        return null;
                    }

                    @Override
                    public void writeTo(BufferedSink bufferedSink) throws IOException {
                        bufferedSink.write(bytes);
                    }
                };

                // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding
                // since okHTTP will automatically chunk even if the request was not chunked
                // this allows Odo to set the appropriate headers when the server request is made
                if (usedContentLength) {
                    okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE",
                            "content-length:" + contentLength);
                }
            } else {
                okRequestBody = RequestBody.create(null, new byte[0]);
            }

            if ("POST".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.post(okRequestBody);
            } else if ("PUT".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.put(okRequestBody);
            } else if ("DELETE".equals(request.getMethod())) {
                okRequestBuilder = okRequestBuilder.delete(okRequestBody);
            }
        } else if ("OPTIONS".equals(request.getMethod())) {
            // NOT SUPPORTED
        } else if ("HEAD".equals(request.getMethod())) {
            okRequestBuilder = okRequestBuilder.head();
        } else {
            LOG.warn("Unexpected request method %s, giving up", request.getMethod());
            request.setHandled(true);
            return -1;
        }

        Request okRequest = okRequestBuilder.build();
        Response okResponse = okHttpClient.newCall(okRequest).execute();

        // Set status and response message
        response.setStatus(okResponse.code());
        response.setReason(okResponse.message());

        // copy response headers
        for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) {
            String headerName = okResponse.headers().name(headerNum);
            if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) {
                response.addField(headerName, okResponse.headers().value(headerNum));
            }
        }

        // write output to response output stream
        try {
            IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream());
        } catch (Exception e) {
            // ignoring this until we refactor the proxy
            // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to
            // The client still gets all of the data it was expecting
        }

        request.setHandled(true);
        return okResponse.body().contentLength();
    } catch (Exception e) {
        LOG.warn("Caught exception proxying: ", e);
        reportError(e, url, response);
        request.setHandled(true);
        return -1;
    }
}

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

License:Apache License

protected void sendRequest(final ResponseListener listener, final RequestBody requestBody) {
    if (method == null || !isValidMethod(method)) {
        listener.onFailure(null, new IllegalArgumentException("Method is not valid: " + method), null);
        return;/* w  w w . ja  va2 s . c om*/
    }

    Request.Builder requestBuilder = new Request.Builder();

    requestBuilder.headers(headers.build());

    try {
        if (getQueryParamsMap().size() == 0) {
            requestBuilder.url(url);
        } else {
            requestBuilder.url(getURLWithQueryParameters(url, getQueryParamsMap()));

        }
    } catch (MalformedURLException e) {
        listener.onFailure(null, e, null);
        return;
    }

    //A GET request cannot have a body in OKHTTP
    if (!method.equalsIgnoreCase("GET")) {
        requestBuilder.method(method, requestBody);
    } else {
        requestBuilder.get();
    }

    Request request = requestBuilder.build();
    OkHttpClient client = getHttpClient();
    client.newCall(request).enqueue(getCallback(listener));
    client.newCall(request);

}

From source file:com.ichg.service.volley.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();
    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));
    }/*from w ww. jav a  2s.c  o  m*/
    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;
}

From source file:com.magnet.max.android.rest.RequestInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Log.i(TAG, "---------Intercepting url : " + request.method() + " " + request.urlString());

    CallOptions options = requestManager.popRequestOptions(request);
    boolean isCacheEnabled = null != options && null != options.getCacheOptions();
    if (isCacheEnabled) {
        if (options.getCacheOptions().isAlwaysUseCacheIfOffline() && ConnectivityManager.getInstance()
                .getConnectivityStatus() == ConnectivityManager.TYPE_NOT_CONNECTED) {
            Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions());
            if (null != cachedResponse) {
                Log.d(TAG, "-------return from cache when isAlwaysUseCacheIfOffline==true and offline");
                return cachedResponse;
            } else {
                throw new IOException("It's offline and no cached response found");
            }//from  w  w w  .ja v a 2 s .  c  o m
        } else if (options.getCacheOptions().getMaxCacheAge() > 0) { // Return from cache if it's not expired
            Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions());
            if (null != cachedResponse) {
                Log.d(TAG, "-------return from cache when maxCacheAge = "
                        + options.getCacheOptions().getMaxCacheAge());
                return cachedResponse;
            }
        }
    }

    //Add auth token for network call
    String token = null;
    if ((authTokenProvider.isAuthEnabled() && authTokenProvider.isAuthRequired(request))
            && (null != authTokenProvider.getAppToken() || null != authTokenProvider.getUserToken())) {
        String existingToken = request.header(AuthUtil.AUTHORIZATION_HEADER);
        if (null != existingToken && existingToken.startsWith("Basic")) {
            // Already has Basic Auth header, don't overwrite
        } else {
            token = getToken();
        }
    }

    boolean useMock = false;
    if (null != options) {
        if (isCacheEnabled) {
            useMock = options.getCacheOptions().useMock();
        } else if (null != options.getReliableCallOptions()) {
            useMock = options.getReliableCallOptions().useMock();
        }
    }

    Response response = null;
    long startTime = System.currentTimeMillis();
    try {
        // Modify request
        if (null != token || useMock) {
            Request.Builder newRequestBuilder = chain.request().newBuilder();

            if (null != token) {
                newRequestBuilder.header(AuthUtil.AUTHORIZATION_HEADER, AuthUtil.generateOAuthToken(token));
            }

            if (useMock) {
                newRequestBuilder.url(request.urlString().replace(RestConstants.REST_BASE_PATH,
                        RestConstants.REST_MOCK_BASE_PATH));
            }

            response = chain.proceed(newRequestBuilder.build());
        } else {
            response = chain.proceed(request);
        }

        if (null != options && options.isReliable()) { // Reliable call
            requestManager.removeReliableRequest(request);
        }
    } catch (IOException e) {
        //if(null != options && options.isReliable()) { // Reliable call
        //  requestManager.saveReliableRequest(request, null, null, options.getReliableCallOptions(), e.getMessage());
        //  //TODO :
        //  return null;  // Swallow exception
        //} else {
        //  throw e;
        //}
        Log.e(TAG, "error when getting response", e);
        throw e;
    }

    Log.d(TAG,
            "---------Response for url : " + request.method() + " " + request.urlString() + " : code = "
                    + response.code() + ", message = " + response.message() + " in "
                    + (System.currentTimeMillis() - startTime) + " ms");

    //Save/Update response in cache
    if (response.isSuccessful() && isCacheEnabled && (options.getCacheOptions().getMaxCacheAge() > 0
            || options.getCacheOptions().isAlwaysUseCacheIfOffline())) {
        return cacheManager.cacheResponse(request, response, options.getCacheOptions());
    }

    return response;
}

From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.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();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.networkInterceptors().add(new MoesifOkHttp2Interceptor());

    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));
    }/*from ww w .  j a va  2s.  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;
}

From source file:com.mozillaonline.providers.downloads.DownloadThread.java

License:Apache License

/**
 * Executes the download in a separate thread
 *//*w w  w .j a va  2 s  .  co  m*/
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        wakeLock.acquire();

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
        }

        boolean finished = false;
        while (!finished) {
            Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);

            Request.Builder requestBuilder = new Request.Builder();
            InnerState innerState = new InnerState();
            setupDestinationFile(state, innerState);
            addRequestHeaders(innerState, requestBuilder);
            requestBuilder.url(state.mRequestUri);

            Request request = requestBuilder.build();
            Call call = mOkHttpClient.newCall(request);
            try {
                executeDownload(innerState, state, call);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                call.cancel();
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = Downloads.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
        finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (mOkHttpClient != null) {
            mOkHttpClient.cancel(null);
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData,
                state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.mHasActiveThread = false;
    }
}

From source file:com.mummyding.app.leisure.database.cache.cache.DailyCache.java

License:Open Source License

public void load() {
    Request.Builder builder = new Request.Builder();
    builder.url(DailyApi.daily_url);
    Request request = builder.build();
    HttpUtil.enqueue(request, new Callback() {
        @Override/*from w  w w.  j  a  v a  2  s .c  om*/
        public void onFailure(Request request, IOException e) {
            mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful() == false) {
                mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
                return;
            }
            String res = response.body().string();

            ArrayList<String> collectionTitles = new ArrayList<String>();
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).isCollected() == 1) {
                    collectionTitles.add(mList.get(i).getTitle());
                }
            }

            List<StoryBean> oldList = new ArrayList<StoryBean>();
            List<StoryBean> newList = new ArrayList<StoryBean>();

            for (StoryBean storyBean : mList) {
                oldList.add(storyBean);
            }

            Gson gson = new Gson();
            DailyBean dailyBean = gson.fromJson(res, DailyBean.class);
            StoryBean[] storyBeans = dailyBean.getStories();
            for (StoryBean storyBeen : storyBeans) {
                newList.add(storyBeen);
            }

            loadOld(dailyBean.getDate(), oldList, newList);

        }
    });
}