List of usage examples for com.squareup.okhttp Call enqueue
public void enqueue(Callback responseCallback)
From source file:abtlibrary.utils.as24ApiClient.ApiClient.java
License:Apache License
/** * Execute HTTP call asynchronously.//from w w w . ja v a2 s. c o m * * @see #execute(Call, Type) * @param <T> Type * @param call The callback to be executed when the API call finishes * @param returnType Return type * @param callback ApiCallback */ @SuppressWarnings("unchecked") public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) { call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { callback.onFailure(new ApiException(e), 0, null); } @Override public void onResponse(Response response) throws IOException { T result; try { result = (T) handleResponse(response, returnType); } catch (ApiException e) { callback.onFailure(e, response.code(), response.headers().toMultimap()); return; } callback.onSuccess(result, response.code(), response.headers().toMultimap()); } }); }
From source file:appewtc.masterung.testdrivinglicense.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//from ww w . 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:appewtc.masterung.testdrivinglicense.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 w w.j a va2s. c o m*/ 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(); } } // onResponse }); }
From source file:appewtc.masterung.testdrivinglicense.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//w w w . jav a 2s .c o m public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { finish(); } }); }
From source file:at.aau.itec.android.mediaplayer.dash.DashMediaExtractor.java
License:Open Source License
/** * Makes async segment requests to fill the cache up to a certain level. *///from w ww . j a va2 s .c om private void fillFutureCache(Representation representation) { int segmentsToBuffer = (int) Math.ceil((double) mMinBufferTimeUs / mRepresentation.segmentDurationUs); for (int i = mCurrentSegment + 1; i < Math.min(mCurrentSegment + 1 + segmentsToBuffer, mRepresentation.segments.size()); i++) { if (!mFutureCache.containsKey(i) && !mFutureCacheRequests.containsKey(i)) { Segment segment = representation.segments.get(i); Request request = buildSegmentRequest(segment); Call call = mHttpClient.newCall(request); CachedSegment cachedSegment = new CachedSegment(i, segment, representation); // segment could be accessed through representation by i call.enqueue(new SegmentDownloadCallback(cachedSegment)); mFutureCacheRequests.put(i, call); } } }
From source file:butter.droid.base.providers.subs.SubsProvider.java
License:Open Source License
/** * @param context Context//from ww w .j av a 2 s .co m * @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 = ButterApplication.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:cc.arduino.mvd.services.HttpService.java
License:Apache License
/** * Perform a POST request to the service * * @param url/* w w w . ja v a 2 s .c om*/ * @param json * @return * @throws IOException */ private void post(String url, String json) { MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, json); Log.d(TAG, "POST: " + url); final Request request = new Request.Builder().url(url).post(body).build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException exception) { // Meh, don't do anything... exception.printStackTrace(); } @Override public void onResponse(final Response response) throws IOException { // Meh, don't do anything... Log.d(TAG, request.toString()); } }); }
From source file:cc.arduino.mvd.services.HttpService.java
License:Apache License
/** * Get something from the service/*from w w w . jav a 2s.c om*/ * * @param url * @return * @throws IOException */ private void get(String url) throws IOException { MediaType JSON = MediaType.parse("application/json; charset=utf-8"); final Request request = new Request.Builder().url(url).get().build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException exception) { // Meh, don't do anything... exception.printStackTrace(); } @Override public void onResponse(final Response response) throws IOException { try { String body = new String(response.body().bytes()); JSONObject json = new JSONObject(body); handleKeyValFromHttp(json.getString("code"), json.getString("pin"), json.getString("value")); } catch (JSONException e) { e.printStackTrace(); } } }); }
From source file:cn.wochu.wh.net.OkHttpClientManager.java
License:Apache License
/** * /* w ww. ja v a 2 s .com*/ * * @param url * @param destFileDir * @param callback */ private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback) { final Request request = new Request.Builder().url(url).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException e) { sendFailedStringCallback(request, e, callback); } @Override public void onResponse(Response response) { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { is = response.body().byteStream(); File file = new File(destFileDir, getFileName(url)); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); //??? sendSuccessResultCallback(file.getAbsolutePath(), callback); } catch (IOException e) { sendFailedStringCallback(response.request(), e, callback); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void illegalToExecuteTwice() throws Exception { server.enqueue(new MockResponse().setBody("abc").addHeader("Content-Type: text/plain")); Request request = new Request.Builder().url(server.getUrl("/")).header("User-Agent", "SyncApiTest").build(); Call call = client.newCall(request); FiberOkHttpUtil.executeInFiber(call); try {/* w w w . j a va 2s . c o m*/ FiberOkHttpUtil.executeInFiber(call); fail(); } catch (IllegalStateException e) { assertEquals("Already Executed", e.getMessage()); } try { call.enqueue(callback); fail(); } catch (IllegalStateException e) { assertEquals("Already Executed", e.getMessage()); } assertEquals("SyncApiTest", server.takeRequest().getHeader("User-Agent")); }