List of usage examples for com.squareup.okhttp Response body
ResponseBody body
To view the source code for com.squareup.okhttp Response body.
Click Source Link
From source file:butter.droid.base.providers.media.TVProvider.java
License:Open Source License
/** * Fetch the list of movies from EZTV/*from w w w . j a v a 2 s.c o m*/ * * @param currentList Current shown list to be extended * @param requestBuilder Request to be executed * @param callback Network callback * @return Call */ private Call fetchList(final ArrayList<Media> currentList, final Request.Builder requestBuilder, final Filters filters, final Callback callback) { return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { String url = requestBuilder.build().urlString(); if (CURRENT_API >= API_URLS.length - 1) { callback.onFailure(e); } else { if (url.contains(API_URLS[CURRENT_API])) { url = url.replace(API_URLS[CURRENT_API], API_URLS[CURRENT_API + 1]); CURRENT_API++; } else { url = url.replace(API_URLS[CURRENT_API - 1], API_URLS[CURRENT_API]); } requestBuilder.url(url); fetchList(currentList, requestBuilder, filters, callback); } } @Override public void onResponse(Response response) throws IOException { try { if (response.isSuccessful()) { String responseStr = response.body().string(); ArrayList<LinkedTreeMap<String, Object>> list = null; if (responseStr.isEmpty()) { list = new ArrayList<>(); } else { list = (ArrayList<LinkedTreeMap<String, Object>>) mGson.fromJson(responseStr, ArrayList.class); } TVReponse result = new TVReponse(list); if (list == null) { callback.onFailure(new NetworkErrorException("Empty response")); } else { ArrayList<Media> formattedData = result.formatListForPopcorn(currentList); callback.onSuccess(filters, formattedData, list.size() > 0); return; } } } catch (Exception e) { callback.onFailure(e); } callback.onFailure(new NetworkErrorException("Couldn't connect to TVAPI")); } }); }
From source file:butter.droid.base.providers.media.TVProvider.java
License:Open Source License
@Override public Call getDetail(ArrayList<Media> currentList, Integer index, final Callback callback) { Request.Builder requestBuilder = new Request.Builder(); String url = API_URLS[CURRENT_API] + "show/" + currentList.get(index).videoId; requestBuilder.url(url);//from w w w .ja v a 2 s .co m requestBuilder.tag(MEDIA_CALL); Timber.d("TVProvider", "Making request to: " + url); return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { callback.onFailure(e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); LinkedTreeMap<String, Object> map = mGson.fromJson(responseStr, LinkedTreeMap.class); TVReponse result = new TVReponse(map); if (map == null) { callback.onFailure(new NetworkErrorException("Empty response")); } else { ArrayList<Media> formattedData = result.formatDetailForPopcorn(); if (formattedData.size() > 0) { callback.onSuccess(null, formattedData, true); return; } callback.onFailure(new IllegalStateException("Empty list")); return; } } callback.onFailure(new NetworkErrorException("Couldn't connect to TVAPI")); } }); }
From source file:butter.droid.base.providers.media.VodoProvider.java
License:Open Source License
/** * Fetch the list of movies from YTS//from w w w . j a v a2s. c o m * * @param currentList Current shown list to be extended * @param requestBuilder Request to be executed * @param callback Network callback * @return Call */ private Call fetchList(final ArrayList<Media> currentList, final Request.Builder requestBuilder, final Filters filters, final Callback callback) { return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { String url = requestBuilder.build().urlString(); if (CURRENT_API >= API_URLS.length - 1) { callback.onFailure(e); } else { if (url.contains(API_URLS[CURRENT_API])) { url = url.replace(API_URLS[CURRENT_API], API_URLS[CURRENT_API + 1]); url = url.replace(API_URLS[CURRENT_API], API_URLS[CURRENT_API + 1]); CURRENT_API++; } else { url = url.replace(API_URLS[CURRENT_API - 1], API_URLS[CURRENT_API]); url = url.replace(API_URLS[CURRENT_API - 1], API_URLS[CURRENT_API]); } requestBuilder.url(url); fetchList(currentList, requestBuilder, filters, callback); } } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String responseStr; try { responseStr = response.body().string(); } catch (SocketException e) { onFailure(response.request(), new IOException("Socket failed")); return; } VodoResponse result; try { result = mGson.fromJson(responseStr, VodoResponse.class); } catch (IllegalStateException e) { onFailure(response.request(), new IOException("JSON Failed")); return; } catch (JsonSyntaxException e) { onFailure(response.request(), new IOException("JSON Failed")); return; } if (result == null) { callback.onFailure(new NetworkErrorException("No response")); } else if (result.downloads == null || result.downloads.size() <= 0) { callback.onFailure(new NetworkErrorException("No movies found")); } else { ArrayList<Media> formattedData = result.formatForApp(currentList); callback.onSuccess(filters, formattedData, true); return; } } onFailure(response.request(), new IOException("Couldn't connect to Vodo")); } }); }
From source file:butter.droid.base.providers.subs.SubsProvider.java
License:Open Source License
/** * @param context Context/*from w ww . j a v a2 s . c om*/ * @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:butter.droid.base.providers.subs.YSubsProvider.java
License:Open Source License
private void fetch(Request.Builder requestBuilder, final Movie media, final Callback callback) { enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() { @Override/*from w w w.ja va 2s. co m*/ public void onFailure(Request request, IOException e) { callback.onFailure(e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); YSubsResponse result = mGson.fromJson(responseStr, YSubsResponse.class); callback.onSuccess(result.formatForPopcorn(PREFIX, LANGUAGE_MAPPING).get(media.imdbId)); } } }); }
From source file:butter.droid.base.youtube.YouTubeData.java
License:Open Source License
/** * Calculate the YouTube URL to load the video. Includes retrieving a token that YouTube * requires to play the video.// w w w . j av a 2 s.c o m * * @param quality quality of the video. 17=low, 18=high * @param fallback whether to fallback to lower quality in case the supplied quality is not available * @param videoId the id of the video * @return the url string that will retrieve the video * @throws java.io.IOException */ public static String calculateYouTubeUrl(String quality, boolean fallback, String videoId) throws IOException { String uriStr = null; OkHttpClient client = ButterApplication.getHttpClient(); Request.Builder request = new Request.Builder(); request.url(YOUTUBE_VIDEO_INFORMATION_URL + videoId); Call call = client.newCall(request.build()); Response response = call.execute(); String infoStr = response.body().string(); String[] args = infoStr.split("&"); Map<String, String> argMap = new HashMap<String, String>(); for (String arg : args) { String[] valStrArr = arg.split("="); if (valStrArr.length >= 2) { argMap.put(valStrArr[0], URLDecoder.decode(valStrArr[1])); } } //Find out the URI string from the parameters //Populate the list of formats for the video String fmtList = URLDecoder.decode(argMap.get("fmt_list"), "utf-8"); ArrayList<Format> formats = new ArrayList<Format>(); if (null != fmtList) { String formatStrs[] = fmtList.split(","); for (String lFormatStr : formatStrs) { Format format = new Format(lFormatStr); formats.add(format); } } //Populate the list of streams for the video String streamList = argMap.get("url_encoded_fmt_stream_map"); if (null != streamList) { String streamStrs[] = streamList.split(","); ArrayList<VideoStream> streams = new ArrayList<VideoStream>(); for (String streamStr : streamStrs) { VideoStream lStream = new VideoStream(streamStr); streams.add(lStream); } //Search for the given format in the list of video formats // if it is there, select the corresponding stream // otherwise if fallback is requested, check for next lower format int formatId = Integer.parseInt(quality); Format searchFormat = new Format(formatId); while (!formats.contains(searchFormat) && fallback) { int oldId = searchFormat.getId(); int newId = getSupportedFallbackId(oldId); if (oldId == newId) { break; } searchFormat = new Format(newId); } int index = formats.indexOf(searchFormat); if (index >= 0) { VideoStream searchStream = streams.get(index); uriStr = searchStream.getUrl(); } } //Return the URI string. It may be null if the format (or a fallback format if enabled) // is not found in the list of formats for the video return uriStr; }
From source file:cc.arduino.mvd.services.HttpService.java
License:Apache License
/** * Get something from the service/* w ww .j a v a2 s . c o m*/ * * @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:client.lib.Client.java
public int test(String url) throws IOException, MalformedURLException { int successful = 0; URL entry = new URL(url); Request request = new Request.Builder().url(entry.toString()).build(); Response response = httpClient.newCall(request).execute(); System.out.println(response.protocol()); try {//from w w w. jav a 2 s . c om JSONObject json = new JSONObject(response.body().string()); JSONArray urls = json.getJSONArray("urls"); for (int i = 0; i < urls.length(); ++i) { response = request(http2Client, new URL(urls.getString(i))); if (response != null) { successful++; } } URL finish = new URL(entry.getProtocol(), entry.getHost(), entry.getPort(), json.getString("finish")); request(httpClient, finish); } catch (JSONException e) { System.out.println(e.getMessage()); } return successful; }
From source file:client.ui.Container.java
public void test(String URL) throws IOException, MalformedURLException { Thread worker = new Thread() { public void run() { String error = null;//from ww w . j av a 2 s .c om try { int http = 0; int h2 = 0; URL entry = new URL(URL); Request request = new Request.Builder().url(entry.toString()).build(); Response response = httpClient.newCall(request).execute(); log("Getting urls to test from: " + entry.toString()); JSONObject json = new JSONObject(response.body().string()); JSONArray urls = json.getJSONArray("urls"); progress.setMaximum(urls.length()); progress.setIndeterminate(false); SocketFactory factory = SSLSocketFactory.getDefault(); JSONArray certs = new JSONArray(); for (int i = 0; i < urls.length(); ++i) { URL url = new URL(urls.getString(i)); if ("https".equals(url.getProtocol())) { certs.put(getCert(factory, url)); } response = request(httpClient, url); if (response != null) { http++; } response = request(http2Client, url); if (response != null) { h2++; } progress.setValue(progress.getValue() + 1); } URL finish = new URL(entry.getProtocol(), entry.getHost(), entry.getPort(), json.getString("finish")); json = new JSONObject(); json.put("certs", certs); response = request(httpClient, finish, json.toString()); json = new JSONObject(response.body().string()); String vcode = json.getString("vcode"); if (vcode.length() > 0) { vcodeLabel.setText("Please, copy the VCODE:"); vcodeOutput.setText(vcode); vcodeOutput.setEnabled(true); } JOptionPane.showMessageDialog(Container.this, "Successful requests: " + "\nHTTP/1.1: " + Integer.toString(http) + "/" + Integer.toString(urls.length()) + "\nHTTP/2: " + Integer.toString(h2) + "/" + Integer.toString(urls.length()), "Completed!", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { error = e.getMessage(); } if (error != null) { System.out.println(error); JOptionPane.showMessageDialog(Container.this, "Error: " + error, "Error", JOptionPane.ERROR_MESSAGE); progress.setIndeterminate(false); progress.setValue(0); } campaignInput.setEnabled(true); workerInput.setEnabled(true); urlInput.setEnabled(true); button.setEnabled(true); } }; worker.start(); }
From source file:clienteconecta.ventanaPrincipal.java
public static String getString(String metodo, RequestBody formBody) { try {// w w w .j a v a 2s. com URL dire = new URL("http://0.0.0.0:5000/" + metodo); Request pide = new Request.Builder().url(dire).post(formBody).build(); Response recibe = webClient.newCall(pide).execute();//Aqui obtiene la respuesta en dado caso si hayas pues un return en python String cadenaDevuelta = recibe.body().string();//y este seria el string de las respuesta return cadenaDevuelta; } catch (MalformedURLException ex) { //java.util.logging.Logger.getLogger(edd_lineal_nlineal.Conexion.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { // java.util.logging.Logger.getLogger(edd_lineal_nlineal.Conexion.class.getName()).log(Level.SEVERE, null, ex); } return null; }