Download binary file from OKHTTP

前端 未结 6 1784
不知归路
不知归路 2020-11-22 11:53

I am using OKHTTP client for networking in my android application.

This example shows how to upload binary file. I would like to know how to get inputstream of binary

6条回答
  •  盖世英雄少女心
    2020-11-22 12:49

    Getting ByteStream from OKHTTP

    I've been digging around in the Documentation of OkHttp you need to go this way

    use this method :

    response.body().byteStream() wich will return an InputStream

    so you can simply use a BufferedReader or any other alternative

    OkHttpClient client = new OkHttpClient();
    request = new Request.Builder().url("URL string here")
                         .addHeader("X-CSRFToken", csrftoken)
                         .addHeader("Content-Type", "application/json")
                         .build();
    response = getClient().newCall(request).execute();
    
    InputStream in = response.body().byteStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String result, line = reader.readLine();
    result = line;
    while((line = reader.readLine()) != null) {
        result += line;
    }
    System.out.println(result);
    response.body().close();
    

提交回复
热议问题