Example usage for com.squareup.okhttp OkHttpClient newCall

List of usage examples for com.squareup.okhttp OkHttpClient newCall

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient newCall.

Prototype

public Call newCall(Request request) 

Source Link

Document

Prepares the request to be executed at some point in the future.

Usage

From source file:pct.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.//  ww w.  j a  va 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 = PopcornApplication.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:tk.breezy64.pantex.core.Util.java

private static Response getHttpResponse(String url, OkHttpClient client, String[]... headers)
        throws IOException {
    Request.Builder reqb = new Request.Builder().url(url).get().addHeader("User-Agent", USER_AGENT);
    for (String[] head : headers) {
        reqb.addHeader(head[0], head[1]);
    }/*from  w  ww  .  j a  v  a 2  s  .  c o m*/
    Request req = reqb.build();

    return client.newCall(req).execute();
}

From source file:tk.breezy64.pantex.core.Util.java

public static String post(String url, Map<String, String> params) throws IOException {
    OkHttpClient client = getClient(DEFAULT_SESSION);
    FormEncodingBuilder b = new FormEncodingBuilder();
    for (Map.Entry<String, String> e : params.entrySet()) {
        b.add(e.getKey(), e.getValue());
    }/*w ww . j a va  2  s. co  m*/

    Request req = new Request.Builder().post(b.build()).url(url).build();

    Response r = client.newCall(req).execute();
    System.out.println("Result: " + r.toString());
    return r.body().string();
}

From source file:Utils.TestWebServer.java

public static String getString(String metodo, RequestBody formBody) {

    OkHttpClient webClient = new OkHttpClient();

    try {/*from   w  w w. ja va  2s.c om*/
        URL url = new URL("http://localhost:5000/" + metodo);
        Request request = new Request.Builder().url(url).post(formBody).build();
        Response response = webClient.newCall(request).execute();//Aqui obtiene la respuesta en dado caso si hayas pues un return en python
        String response_string = response.body().string();//y este seria el string de las respuesta
        return response_string;
    } catch (MalformedURLException ex) {
        java.util.logging.Logger.getLogger(TestWebServer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        java.util.logging.Logger.getLogger(TestWebServer.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:zack.examples.questiondb.database.QuestionsOpenHelper.java

License:Apache License

@Override
public void onCreate(SQLiteDatabase db) {
    // executing the schema - DDL (data definition language)
    db.execSQL(DBContract.QuestionsTable.SCHEMA);
    db.execSQL(DBContract.AnswersTable.SCHEMA);

    try {//from   w  w w  . j  ava  2s. c  om
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder().url(DB_CONTENT_URL).build();

        Response response = client.newCall(request).execute();
        String[] sql = response.body().string().split("===");

        // executing data insertion - DML (data manipulation language)
        for (String statement : sql) {
            db.execSQL(statement.trim());
        }

    } catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG, e.getMessage());
    }

}

From source file:zblibrary.demo.manager.HttpRequest.java

License:Apache License

/**
 * @param client//from w w  w. j  a  va2 s  .  c o m
 * @param request
 * @return
 * @throws Exception
 */
private JSONObject getResponseObject(OkHttpClient client, Request request) throws Exception {
    if (client == null || request == null) {
        Log.e(TAG, "getResponseObject  client == null || request == null >> return null;");
        return null;
    }
    Response response = client.newCall(request).execute();
    return response.isSuccessful() ? new JSONObject(response.body().string()) : null;
}