List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request 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)); }/* w w w . j a va 2s. com*/ 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.inductiveautomation.ignition.examples.reporting.datasource.common.RestJsonDataSource.java
/** * Attempts to connect to a Url using {@link OkHttpClient} and return the body of the reply as a String, if it is * JSON mime type.//from w w w. j av a 2 s. com * @param url String specifying the * @return the body of the http response received from the specified Url */ private String collectData(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); // get headers to check the content type out of Headers headers = null; if (response != null) { headers = response.headers(); } // at least try to make sure we have JSON data. boolean isJSON = false; if (headers != null) { isJSON = MediaType.parse(headers.get("Content-Type")).equals(JSON); } return isJSON ? response.body().string() : ""; }
From source file:com.leo.cattle.data.net.ApiConnection.java
License:Apache License
private void connectToApi(String token) { OkHttpClient okHttpClient = this.createClient(); final Request request = new Request.Builder().url(this.url) .addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON).addHeader(CONTENT_AUTH_HEADER, token).get() .build();/*from w ww. j av a2s. c o m*/ try { this.response = okHttpClient.newCall(request).execute().body().string(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.leo.cattle.presentation.gcm.RegistrationIntentService.java
License:Open Source License
private void connectToApi(String token) { OkHttpClient okHttpClient = this.createClient(); final Request request = new Request.Builder() .url("http://13.76.128.53:8000/api/v1/me/tokens?gcmToken=" + token) .addHeader("X-MANADOR-KEY", AndroidApplication.sessionUser.getAccessToken()).get().build(); try {/* w w w.j av a 2 s . c o m*/ //String response = okHttpClient.newCall(request).execute().body().string(); Response httpResponse = okHttpClient.newCall(request).execute(); if (httpResponse.code() == 200) { //success Log.i(TAG, "GCM Registration Token: send to server" + token); } else { Log.i(TAG, "GCM Registration Token: send to server failed" + token); Log.i(TAG, "User Token" + AndroidApplication.sessionUser.getAccessToken()); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.liferay.mobile.android.auth.CookieSignIn.java
License:Open Source License
protected Call signIn() throws Exception { if (!(session.getAuthentication() instanceof CookieAuthentication)) { throw new Exception("Can't sign in if authentication implementation is not " + "CookieAuthentication"); }//w w w . j a v a 2 s . com CookieAuthentication cookieAuthentication = getCookieAuthentication(session.getAuthentication()); username = cookieAuthentication.getUsername(); password = cookieAuthentication.getPassword(); cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); OkHttpClient client = new OkHttpClient(); Authenticator authenticator = authenticators.get(session.getServer()); if (authenticator != null) { client.setAuthenticator(authenticator); } client.setCookieHandler(cookieManager); client.setFollowRedirects(true); Builder builder = getBuilder(session, username, password); return client.newCall(builder.build()); }
From source file:com.liferay.mobile.android.http.client.OkHttpClientImpl.java
License:Open Source License
protected Response send(Builder builder, final Request request) throws Exception { builder = builder.url(request.getURL()); builder.tag(request.getTag());//from www . jav a 2 s. c om OkHttpClient client = getClient(request.getConnectionTimeout()); authenticate(client, request); addHeaders(builder, request); Call call = client.newCall(builder.build()); final Callback callback = request.getCallback(); if (callback == null) { return new Response(call.execute()); } else { sendAsync(call, callback); return null; } }
From source file:com.liferay.mobile.screens.viewsets.defaultviews.webcontent.display.WebContentDisplayView.java
License:Open Source License
public WebViewClient getWebViewClientWithCustomHeader() { return new WebViewClient() { @Override// w ww. ja v a 2 s.com public WebResourceResponse shouldInterceptRequest(WebView view, String url) { return getResource(url.trim()); } @Override @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return getResource(request.getUrl().toString()); } private WebResourceResponse getResource(String url) { try { OkHttpClient httpClient = LiferayServerContext.getOkHttpClientNoCache(); com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder() .url(url); Request request = builder.build(); com.squareup.okhttp.Response response = httpClient.newCall(request).execute(); return new WebResourceResponse( response.header("content-type", response.body().contentType().type()), response.header("content-encoding", "utf-8"), response.body().byteStream()); } catch (Exception e) { return null; } } }; }
From source file:com.liferay.mobile.sdk.auth.CookieSignIn.java
License:Open Source License
public static void signIn(Config config, CookieCallback callback) { try {/*from w w w .jav a 2 s .c o m*/ Authentication auth = config.auth(); if (!(auth instanceof BasicAuthentication)) { throw new Exception( "Can't sign in if authentication implementation is not " + "BasicAuthentication"); } OkHttpClient client = new OkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); client.setFollowRedirects(true); Builder builder = new Builder(); MediaType contentType = MediaType.parse("application/x-www-form-urlencoded"); builder.post(RequestBody.create(contentType, getBody((BasicAuthentication) auth))); builder.addHeader("Cookie", "COOKIE_SUPPORT=true;"); builder.url(getLoginURL(config.server())); Call call = client.newCall(builder.build()); call.enqueue(getCallback(callback, cookieManager)); } catch (Exception e) { callback.onFailure(e); } }
From source file:com.liferay.mobile.sdk.SDKBuilder.java
License:Open Source License
public Discovery discover(String url, String context, int portalVersion) throws Exception { if ("portal".equals(context)) { context = ""; }/*from w w w .j a va 2s . c om*/ if (portalVersion == 62) { if (Validator.isNotNull(context)) { context = "/" + context; } url = String.format("%s%s/api/jsonws?discover", url, context); } else if (portalVersion == 7) { url = String.format("%s/api/jsonws?discover&contextName=%s", url, context); } OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected HTTP response: " + response); } if (portalVersion == 7) { JSONParser.registerTypeAdapter(Discovery.class, new DiscoveryDeserializer()); JSONParser.registerTypeAdapter(Action.class, new ActionDeserializer()); } return JSONParser.fromJSON(response.body().string(), Discovery.class); }
From source file:com.mamashai.pingxx.PingxxAndroidModule.java
License:Open Source License
@Kroll.method public void pay(Object arg) { HashMap<String, String> kd = (HashMap<String, String>) arg; OkHttpClient client = new OkHttpClient(); /*//from www . j ava 2 s .c o m RequestBody formBody = new FormEncodingBuilder() .add("order_no", kd.get("order_no")) .add("amount", kd.get("amount")) .add("channel", kd.get("channel")) .build(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); */ String url = kd.get("url") + "?order_no=" + kd.get("order_no") + "&amount=" + kd.get("amount") + "&channel=" + kd.get("channel"); Log.d(LCAT, "url :" + url); Request request = new Request.Builder().url(url).build(); try { Response response = client.newCall(request).execute(); if (response.code() >= 200 && response.code() <= 300) { String data = response.body().string(); Log.d(LCAT, "data:" + data); Intent intent = new Intent(); String packageName = _app.getAppCurrentActivity().getPackageName(); ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity"); intent.setComponent(componentName); intent.putExtra(PaymentActivity.EXTRA_CHARGE, data); TiActivitySupport support = (TiActivitySupport) TiApplication.getAppCurrentActivity(); support.launchActivityForResult(intent, REQUEST_CODE_PAYMENT, this); Log.d(LCAT, "after launch Activity"); } else { HashMap<String, Object> event = new HashMap<String, Object>(); event.put("code", "error"); event.put("text", "charge" + response); fireEvent("ping_paid", event); Log.d(LCAT, "request error"); } } catch (Exception e) { } }