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.near.chimerarevo.fragments.ProductsListFragment.java

License:Apache License

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    if (totalItemCount < 10)
        return;//  ww  w.  j  a va  2 s  . c o m

    byte visibleThreshold = 1;

    if (!isTaskRunning && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {

        page++;
        counter = page;

        Request.Builder rb = new Request.Builder().tag(FRAGMENT_TAG);

        if (mCat.getSelectedItemPosition() > 0 && mBrand.getSelectedItemPosition() > 0)
            rb.url(URLUtils.getProductsUrl(counter,
                    String.valueOf(catIdList.get(mCat.getSelectedItemPosition() - 1)),
                    brandsList.get(mBrand.getSelectedItemPosition())));
        else if (mCat.getSelectedItemPosition() > 0)
            rb.url(URLUtils.getProductsUrl(counter,
                    String.valueOf(catIdList.get(mCat.getSelectedItemPosition() - 1)), ""));
        else if (mBrand.getSelectedItemPosition() > 0)
            rb.url(URLUtils.getProductsUrl(counter, "", brandsList.get(mBrand.getSelectedItemPosition())));
        else
            rb.url(URLUtils.getProductsUrl(counter, "", ""));

        isTaskRunning = true;
        OkHttpUtils.getInstance().newCall(rb.build()).enqueue(new GetProductsCallback());

        if (mLoadingToolbar != null)
            mLoadingToolbar.setVisibility(View.VISIBLE);
    }
}

From source file:com.northernwall.hadrian.module.maven.MavenHelper.java

License:Apache License

@Override
public List<String> readArtifactVersions(Module module) {
    List<String> versions = new LinkedList<>();
    if (module.getMavenGroupId() != null && !module.getMavenGroupId().isEmpty()
            && module.getMavenArtifactId() != null && !module.getMavenArtifactId().isEmpty()) {
        try {//from w  ww  .j  a v a2  s  . c o m
            Request.Builder builder = new Request.Builder();
            String mavenRepo = parameters.getString(Const.MAVEN_URL, Const.MAVEN_URL_DEFAULT);
            String url = mavenRepo + module.getMavenGroupId().replace(".", "/") + "/"
                    + module.getMavenArtifactId() + "/maven-metadata.xml";
            builder.url(url);
            String mavenUsername = parameters.getString(Const.MAVEN_USERNAME, Const.MAVEN_USERNAME_DEFAULT);
            String mavenPassword = parameters.getString(Const.MAVEN_PASSWORD, Const.MAVEN_PASSWORD_DEFAULT);
            if (!mavenUsername.equals(Const.MAVEN_USERNAME_DEFAULT)) {
                String credential = Credentials.basic(mavenUsername, mavenPassword);
                builder.header("Authorization", credential);
            }
            Request request = builder.build();
            Response response = client.newCall(request).execute();

            try (InputStream inputStream = response.body().byteStream()) {
                versions = processMavenStream(inputStream);
            }
        } catch (Exception ex) {
            logger.error("Error reading maven version from {} {}, {}", module.getMavenGroupId(),
                    module.getMavenArtifactId(), ex.getMessage());
        }
    }

    return versions;
}

From source file:com.open.taogubaweex.adapter.DefaultWebSocketAdapter.java

License:Apache License

@Override
public void connect(String url, @Nullable String protocol, EventListener listener) {
    this.eventListener = listener;
    OkHttpClient okHttpClient = new OkHttpClient();

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

    if (protocol != null) {
        builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol);
    }/*from   www . ja va  2 s.c om*/
    url = url + "?token=" + URLEncoder.encode("android_1262670&B05016B999132BC0C7C69297B1748CB6");
    builder.url(url);

    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {

            //                public void checkClientTrusted(X509Certificate[] certs, String authType) {
            //                    System.out.println("checkClientTrusted1");
            //                }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                System.out.println("checkClientTrusted2");
            }

            //                public void checkServerTrusted(X509Certificate[] certs,
            //                                               String authType) {
            //                    System.out.println("checkServerTrusted1");
            //                }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                System.out.println("checkServerTrusted2");
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLSocketFactory factory = sslContext.getSocketFactory();
    okHttpClient.setSslSocketFactory(factory);

    WebSocketCall.create(okHttpClient, builder.build()).enqueue(new WebSocketListener() {
        @Override
        public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException {
            ws = webSocket;
            eventListener.onOpen();
        }

        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            eventListener.onMessage(payload.readUtf8());
            payload.close();
        }

        @Override
        public void onPong(Buffer payload) {

        }

        @Override
        public void onClose(int code, String reason) {
            eventListener.onClose(code, reason, true);
        }

        @Override
        public void onFailure(IOException e) {
            e.printStackTrace();
            if (e instanceof EOFException) {
                eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(),
                        WebSocketCloseCodes.CLOSE_NORMAL.name(), true);
            } else {
                eventListener.onError(e.getMessage());
            }
        }
    });
}

From source file:com.parse.ParseOkHttpClient.java

License:Open Source License

@Override
/* package */ Request getRequest(ParseHttpRequest parseRequest) throws IOException {
    Request.Builder okHttpRequestBuilder = new Request.Builder();
    ParseHttpRequest.Method method = parseRequest.getMethod();
    // Set method
    switch (method) {
    case GET:/*from w  ww .  j a  v  a2  s . co m*/
        okHttpRequestBuilder.get();
        break;
    case DELETE:
        okHttpRequestBuilder.delete();
        break;
    case POST:
    case PUT:
        // Since we need to set body and method at the same time for POST and PUT, we will do it in
        // the following.
        break;
    default:
        // This case will never be reached since we have already handled this case in
        // ParseRequest.newRequest().
        throw new IllegalStateException("Unsupported http method " + method.toString());
    }
    // Set url
    okHttpRequestBuilder.url(parseRequest.getUrl());

    // Set Header
    Headers.Builder okHttpHeadersBuilder = new Headers.Builder();
    for (Map.Entry<String, String> entry : parseRequest.getAllHeaders().entrySet()) {
        okHttpHeadersBuilder.add(entry.getKey(), entry.getValue());
    }
    // OkHttp automatically add gzip header so we do not need to deal with it
    Headers okHttpHeaders = okHttpHeadersBuilder.build();
    okHttpRequestBuilder.headers(okHttpHeaders);

    // Set Body
    ParseHttpBody parseBody = parseRequest.getBody();
    ParseOkHttpRequestBody okHttpRequestBody = null;
    if (parseBody instanceof ParseByteArrayHttpBody) {
        okHttpRequestBody = new ParseOkHttpRequestBody(parseBody);
    }
    switch (method) {
    case PUT:
        okHttpRequestBuilder.put(okHttpRequestBody);
        break;
    case POST:
        okHttpRequestBuilder.post(okHttpRequestBody);
        break;
    }
    return okHttpRequestBuilder.build();
}

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 a  v 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.phattn.vnexpressnews.io.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 w w . j  ava  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, length = responseHeaders.size(); i < length; i++) {
        final String name = responseHeaders.name(i);
        final String value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.rsu.nuttanun.testdrivingvlicense.ConfirmScoreActivity.java

public void clickOKConfirm(View view) {

    String urlPHP = "http://swiftcodingthai.com/toey/add_score.php";

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("id_login", loginStrings[0])
            .add("Date", dateString).add("Score", scoreString).build();
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override/*w  ww. jav  a  2  s  . c o  m*/
        public void onFailure(Request request, IOException e) {

        }

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

            Intent intent = new Intent(ConfirmScoreActivity.this, ScoreListView.class);
            intent.putExtra("login", loginStrings);
            startActivity(intent);
            finish();
        }
    });

}

From source file:com.rsu.nuttanun.testdrivingvlicense.ScoreListView.java

private void createListView() {

    String urlPHP = "http://swiftcodingthai.com/toey/get_score_where.php";
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("id_login", loginStrings[0])
            .build();//from w  ww .j a va2  s  . c om
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

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

            String strResponse = response.body().string();
            Log.d("10AugV2", "strResponse ==>" + strResponse);

            try {

                JSONArray jsonArray = new JSONArray(strResponse);

                String[] dateStrings = new String[jsonArray.length()];
                String[] scoreStrings = new String[jsonArray.length()];

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    dateStrings[i] = jsonObject.getString("Date");
                    scoreStrings[i] = jsonObject.getString("Score") + " ?";

                } //for

                CoaurseAdapter coaurseAdapter = new CoaurseAdapter(ScoreListView.this, 1, dateStrings,
                        scoreStrings);
                listView.setAdapter(coaurseAdapter);

            } catch (Exception e) {
                e.printStackTrace();

            }

        } // onRespose
    });

}

From source file:com.rsu.nuttanun.testdrivingvlicense.SignUpActivity.java

private void upLoadNewUser() {

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("Name", nameString)
            .add("Surname", surnameString).add("Age", ageString).add("User", userString)
            .add("Password", passwordString).build();
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override//from   ww  w. j a v  a2 s.  c  om
        public void onFailure(Request request, IOException e) {

        }

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

        }
    });

}

From source file:com.ydh.gva.util.net.volley.toolbox.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();
    okHttpRequestBuilder.addHeader("clientos", "101");
    okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + "");
    okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + "");
    okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + "");

    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*from  ww w  . j  a v  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;
}