List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
From source file:org.wildfly.kubernetes.configmap.ConfigMapOperations.java
License:Open Source License
public boolean configMapExists(OkHttpClient client, String namespace, String name) throws IOException { Request request = new Request.Builder().url(buildUrl(namespace, name)).get().build(); return HttpURLConnection.HTTP_OK == client.newCall(request).execute().code(); }
From source file:org.wildfly.kubernetes.configmap.ConfigMapOperations.java
License:Open Source License
public void updateConfigMap(OkHttpClient client, String namespace, String name, Map<String, String> labels, Collection<Path> files) throws IOException { Request request = new Request.Builder().url(buildUrl(namespace, name)) .put(createJsonPayload(namespace, name, labels, files)).build(); Response response = client.newCall(request).execute(); if (HttpURLConnection.HTTP_OK != response.code()) { readStatusResponse(response);//from w w w . ja v a 2s. c o m } }
From source file:org.wso2.carbon.identity.authenticator.duo.DuoHttp.java
License:Open Source License
public Response executeHttpRequest() throws Exception { String url = "https://" + host + uri; String queryString = createQueryString(); Request.Builder builder = new Request.Builder(); if (method.equals("POST")) { builder.post(RequestBody.create(FORM_ENCODED, queryString)); } else if (method.equals("PUT")) { builder.put(RequestBody.create(FORM_ENCODED, queryString)); } else if (method.equals("GET")) { if (queryString.length() > 0) { url += "?" + queryString; }//from w w w .j a va 2 s . c o m builder.get(); } else if (method.equals("DELETE")) { if (queryString.length() > 0) { url += "?" + queryString; } builder.delete(); } else { throw new UnsupportedOperationException("Unsupported method: " + method); } Request request = builder.url(url).build(); // Set up client. OkHttpClient httpclient = new OkHttpClient(); if (proxy != null) { httpclient.setProxy(proxy); } httpclient.setConnectTimeout(timeout, TimeUnit.SECONDS); httpclient.setWriteTimeout(timeout, TimeUnit.SECONDS); httpclient.setReadTimeout(timeout, TimeUnit.SECONDS); // finish and execute request builder.headers(headers.build()); return httpclient.newCall(builder.build()).execute(); }
From source file:org.xbmc.kore.jsonrpc.HostConnection.java
License:Open Source License
/** * Send an OkHttp POST request//from w ww .j av a2s .c o m * @param request Request to send * @throws ApiException */ private Response sendOkHttpRequest(final OkHttpClient client, final Request request) throws ApiException { try { return client.newCall(request).execute(); } catch (ProtocolException e) { LogUtils.LOGW(TAG, "Got a Protocol Exception when trying to send OkHttp request. " + "Trying again without connection pooling to try to circunvent this", e); // Hack to circumvent a Protocol Exception that occurs when the server returns bogus Status Line // http://forum.kodi.tv/showthread.php?tid=224288 httpClient = getNewOkHttpClientNoKeepAlive(); throw new ApiException(ApiException.IO_EXCEPTION_WHILE_SENDING_REQUEST, e); } catch (IOException e) { LogUtils.LOGW(TAG, "Failed to send OkHttp request.", e); throw new ApiException(ApiException.IO_EXCEPTION_WHILE_SENDING_REQUEST, e); } catch (RuntimeException e) { // Seems like OkHttp throws a RuntimeException when it gets a malformed URL LogUtils.LOGW(TAG, "Got a Runtime exception when sending OkHttp request. Probably a malformed URL.", e); throw new ApiException(ApiException.IO_EXCEPTION_WHILE_SENDING_REQUEST, e); } }
From source file:p1.nd.khan.jubair.mohammadd.popularmovies.sync.MovieSyncAdapter.java
License:Apache License
/** * Method to fetch the movie details from server. * * @param pSortOrder : user preferred order for movie display. * @param pPageNo : page number to fetch the record. *//*from w w w. j ava 2s .c om*/ private void fetchMdbMovie(String pSortOrder, int pPageNo) { OkHttpClient client = new OkHttpClient(); String movieURL = UrlFormatter(pSortOrder, pPageNo); Log.v(LOG_TAG, "URL:" + movieURL); Request request = new Request.Builder().url(movieURL).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e(LOG_TAG, "==onFailure[fetchMdbMovie]:", e); return; } @Override public void onResponse(Response response) throws IOException { try { String jsonData = response.body().string(); if (response.isSuccessful()) { insertMovieContentValues(jsonData); } } catch (IOException | JSONException e) { Log.e(LOG_TAG, "IOException | JSONException: Exception caught: ", e); return; } } }); }
From source file:p1.nd.khan.jubair.mohammadd.popularmovies.sync.ReviewSyncAdapter.java
License:Apache License
private void getMovieReviews(final String movieId) { OkHttpClient client = new OkHttpClient(); String builtUri = Uri.parse(MessageFormat.format(mContext.getString(R.string.MOVIE_REVIEW_URL), movieId)) .buildUpon().appendQueryParameter("api_key", mContext.getString(R.string.PERSONAL_API_KEY)).build() .toString();//from w w w . j a v a 2 s. c o m Log.v(LOG_TAG, "URL:" + builtUri); Request request = new Request.Builder().url(builtUri).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e(LOG_TAG, "==onFailure[getMovieReviews]:", e); return; } @Override public void onResponse(Response response) throws IOException { try { String jsonData = response.body().string(); if (response.isSuccessful()) { insertReviewContentValues(movieId, jsonData); } } catch (IOException | JSONException e) { Log.e(LOG_TAG, "IOException | JSONException: Exception caught: ", e); return; } } }); }
From source file:p1.nd.khan.jubair.mohammadd.popularmovies.sync.TrailerSyncAdapter.java
License:Apache License
private void getMovieTrailers(final String movieId) { OkHttpClient client = new OkHttpClient(); String builtUri = Uri.parse(MessageFormat.format(mContext.getString(R.string.MOVIE_TRAILER_URL), movieId)) .buildUpon().appendQueryParameter("api_key", mContext.getString(R.string.PERSONAL_API_KEY)).build() .toString();/*www . java 2 s. co m*/ Log.v(LOG_TAG, "URL:" + builtUri); Request request = new Request.Builder().url(builtUri).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e(LOG_TAG, "==onFailure[getMovieTrailers]:", e); return; } @Override public void onResponse(Response response) throws IOException { try { String jsonData = response.body().string(); if (response.isSuccessful()) { insertTrailerContentValues(movieId, jsonData); } } catch (IOException | JSONException e) { Log.e(LOG_TAG, "IOException | JSONException: Exception caught: ", e); return; } } }); }
From source file:pb.auth.OAuth.java
License:Apache License
public void generateAndSetAccessToken(String apiKey, String secret) throws ApiException { RequestBody body = RequestBody.create(MediaType.parse("application/json"), "grant_type=client_credentials"); Request authRequest = null;//from ww w.j av a 2 s.c o m String authenticationHeader = base64Encode(apiKey + ":" + secret); authRequest = new Request.Builder().url("https://api.pitneybowes.com/oauth/token").post(body) .addHeader("Authorization", "Basic " + authenticationHeader).build(); OkHttpClient client = new OkHttpClient().setAuthenticator(new TokenAuthenticator()); try { Response response = client.newCall(authRequest).execute(); Gson gson = new Gson(); OAuthServiceResponce fromJson = gson.fromJson(response.body().string(), OAuthServiceResponce.class); setApiKey(apiKey); setSecret(secret); setAccessToken(fromJson.access_token); } catch (IOException e) { throw new ApiException(e); } }
From source file:pct.droid.base.providers.subs.SubsProvider.java
License:Open Source License
/** * @param context Context// www . j a va2 s . com * @param media Media data * @param languageCode Code of language * @param callback Network callback * @return Call */ public static Call download(final Context context, final Media media, final String languageCode, final com.squareup.okhttp.Callback callback) { OkHttpClient client = PopcornApplication.getHttpClient(); if (media.subtitles != null && media.subtitles.containsKey(languageCode)) { try { Request request = new Request.Builder().url(media.subtitles.get(languageCode)).build(); Call call = client.newCall(request); final File subsDirectory = getStorageLocation(context); final String fileName = media.videoId + "-" + languageCode; final File srtPath = new File(subsDirectory, fileName + ".srt"); if (srtPath.exists()) { callback.onResponse(null); return call; } call.enqueue(new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { callback.onFailure(request, e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { InputStream inputStream = null; boolean failure = false; try { subsDirectory.mkdirs(); if (srtPath.exists()) { File to = new File(subsDirectory, "temp" + System.currentTimeMillis()); srtPath.renameTo(to); to.delete(); } inputStream = response.body().byteStream(); String urlString = response.request().urlString(); if (urlString.contains(".zip") || urlString.contains(".gz")) { SubsProvider.unpack(inputStream, srtPath, languageCode); } else if (SubsProvider.isSubFormat(urlString)) { parseFormatAndSave(urlString, srtPath, languageCode, inputStream); } else { callback.onFailure(response.request(), new IOException("FatalParsingException")); failure = true; } } catch (FatalParsingException e) { e.printStackTrace(); callback.onFailure(response.request(), new IOException("FatalParsingException")); failure = true; } catch (FileNotFoundException e) { e.printStackTrace(); callback.onFailure(response.request(), e); failure = true; } catch (IOException e) { e.printStackTrace(); callback.onFailure(response.request(), e); failure = true; } finally { if (inputStream != null) inputStream.close(); if (!failure) callback.onResponse(response); } } else { callback.onFailure(response.request(), new IOException("Unknown error")); } } }); return call; } catch (RuntimeException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } callback.onFailure(null, new IOException("Wrong media")); return null; }
From source file:pct.droid.base.torrent.TorrentService.java
License:Open Source License
private TorrentInfo getTorrentInfo(String torrentUrl) { if (torrentUrl.startsWith("magnet")) { Downloader d = new Downloader(mTorrentSession); Timber.d("Waiting for nodes in DHT"); if (!mDHT.isRunning()) { mDHT.start();/*from ww w. ja v a 2 s .c o m*/ } if (mDHT.nodes() < 1) { mDHT.waitNodes(30); } Timber.d("Nodes in DHT: %s", mDHT.nodes()); Timber.d("Fetching the magnet uri, please wait..."); byte[] data = d.fetchMagnet(torrentUrl, 30000); return TorrentInfo.bdecode(data); } else { OkHttpClient client = PopcornApplication.getHttpClient(); Request request = new Request.Builder().url(torrentUrl).build(); try { Response response = client.newCall(request).execute(); return TorrentInfo.bdecode(response.body().bytes()); } catch (IOException e) { e.printStackTrace(); } } return null; }