Use OkHttp3 To Upload And Download Json File Example

This article will tell you how to use OkHttp3 to upload or download json string or file between web server and android application. You can read Android OkHttp3 Http Get Post Request Example to learn OkHttp for basic operation.

1. All Send Operation Used Key Method.

What ever content do you want to send to server, it will use below key method. The method has two input parameter, one is web url the other is okhttp3.RequestBody object.

If you want to send JSon string, then create a JSon string request body. If you want to send a file then create a file request body.

// Send http request with request body, the body can contain Json string, file or multiple part ( post params and file.)
private void sendRequestBody(String url, RequestBody requestBody)
{
    // Create request builder.
    Request.Builder builder = new Request.Builder();
    // Set url.
    builder = builder.url(url);
    // Post request body.
    builder = builder.post(requestBody);
    // Create request object.
    Request request = builder.build();
    // Get okhttp3.Call object.
    Call call = okHttpClient.newCall(request);

    // Execute the call asynchronously.
    call.enqueue(new Callback() {
        // If request fail.
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG_OK_HTTP_FILE_OPERATE, e.getMessage());
        }

        // If request success.
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            int respCode = response.code();
            String respMsg = response.message();
            String respBody = response.body().string();

            Log.d(TAG_OK_HTTP_FILE_OPERATE, "Response code : " + respCode);
            Log.d(TAG_OK_HTTP_FILE_OPERATE, "Response message : " + respMsg);
            Log.d(TAG_OK_HTTP_FILE_OPERATE, "Response body : " + respBody);
        }
    });
}

2. Send JSon String To Server.

// Json data mime type string value.
String jsonMimeType = "application/json; charset=utf-8";

// Get json string media type.
MediaType jsonContentType = MediaType.parse(jsonMimeType);

// Json string.
String jsonString = "{\"username\":\"jerry\",\"password\":\"1234568\"}";

// Create json string request body
RequestBody jsonRequestBody = RequestBody.create(jsonContentType, jsonString);

sendRequestBody("http://www.bing.com", jsonRequestBody);

3. Upload File To Server.

To upload file to server, first you need to get read external storage permission in android app.

int readExternalStoragePermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
if(readExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
{
    String requirePermission[] = {Manifest.permission.READ_EXTERNAL_STORAGE};

    // Below code will invoke method onRequestPermissionsResult.
    ActivityCompat.requestPermissions(OkHttpFileOperationActivity.this, requirePermission, REQUEST_CODE_READ_EXTERNAL_PERMISSION);
}else {

    // Create upload file content mime type.
    MediaType fileContentType = MediaType.parse("File/*");

    String uploadFileRealPath = "/sdcard/Movies/test.txt";

    // Create file object.
    File file = new File(uploadFileRealPath);

    // Create request body.
    RequestBody requestBody = RequestBody.create(fileContentType, file);

    // Send request body.
    sendRequestBody("http://www.bing.com", requestBody);
}

4. Download File From Server.

// Send http request with request body, the body can contain Json string, file or multiple part ( post params and file.)
private void sendRequestBody(String url, RequestBody requestBody)
{
    // Create request builder.
    Request.Builder builder = new Request.Builder();
    // Set url.
    builder = builder.url(url);
    // Post request body.
    builder = builder.post(requestBody);
    // Create request object.
    Request request = builder.build();
    // Get okhttp3.Call object.
    Call call = okHttpClient.newCall(request);

    // Execute the call asynchronously.
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG_OK_HTTP_FILE_OPERATE, e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            int respCode = response.code();
            String respMsg = response.message();
            String respBody = response.body().string();

            Log.d(TAG_OK_HTTP_FILE_OPERATE, "Response code : " + respCode);
            Log.d(TAG_OK_HTTP_FILE_OPERATE, "Response message : " + respMsg);
            Log.d(TAG_OK_HTTP_FILE_OPERATE, "Response body : " + respBody);


            // Download file local file path.
            String filePath = "/sdcard/Audio/test.mp3";

            // File output stream related object.
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            // File input stream related object.
            InputStream inputStream = response.body().byteStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

            // Read data from input stream.
            byte dataBuf[] = new byte[1024];
            int readLen = bufferedInputStream.read(dataBuf);

            // If read data byte length bigger than -1.
            while (readLen > -1)
            {
                // Write buffer data to output stream.
                bufferedOutputStream.write(dataBuf, 0, readLen);

                // Read data again.
                readLen = bufferedInputStream.read(dataBuf);
            }

            // Close input stream.
            bufferedInputStream.close();

            // Flush and close output stream.
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        }
    });
}

5. Add Custom Request Headers.

// Create request builder.
Request.Builder builder = new Request.Builder();
// Set url.
builder = builder.url(url);
// Add custom header.
builder.addHeader("Domain", "dev2qa.com");

// Change exist header value.
builder.header("User-Agent", "IE");

// Post request body.
builder = builder.post(requestBody);
// Create request object.
Request request = builder.build();
// Get okhttp3.Call object.
Call call = okHttpClient.newCall(request);

6. Create Custom RequestBody.

You can extends okhttp3.RequestBody to create a custom request body class. And then sent it to server use key method in section 1.

RequestBody requestBody = new RequestBody() {
    @Nullable
    @Override
    public MediaType contentType() {
        MediaType ret = MediaType.parse("text/html; charset=utf-8");
        return ret;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        // Get local file input stream.
        FileInputStream fileInputStream = new FileInputStream("/sdcard/Audio/test.mp3");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        
        // Read byte data from input stream. 
        byte buf[] = new byte[1024];
        int readLen = bufferedInputStream.read(buf);
        
        while(readLen > -1)
        {
            // Write read data to server use sink object.
            sink.write(buf, 0 , readLen);

            // Read local file data to byte array again.
            readLen = bufferedInputStream.read(buf);
        }
        
        fileInputStream.close();
        sink.flush();
        sink.close();
    }
};

7. Send Parameters And Multiple Media Content Use MultipartBody.

okhttp3.FormBody is used to send string parameters. okhttp3.RequestBody is used to send multiple media content such as file and json string.

READ :   Android Play Video File From Local SD Card / Web Example

But if you want to send both string parameters and multiple media content, you can use okhttp3.MultipartBody.

// Create upload file content mime type.
MediaType fileContentType = MediaType.parse("File/*");

String uploadFileRealPath = "/sdcard/Movies/test.txt";

// Create file object.
File file = new File(uploadFileRealPath);

// Create request body.
RequestBody requestBody = RequestBody.create(fileContentType, file);

// Create multipart body builder.
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();

// Set type.
multipartBuilder.setType(MultipartBody.FORM);

// Add string parameters.
multipartBuilder.addFormDataPart("name", "jerry");
multipartBuilder.addFormDataPart("password", "12345678");

// Add file content.
multipartBuilder.addPart(requestBody);

// Get multipartbody object.
MultipartBody multipartBody = multipartBuilder.build();

sendRequestBody("http://www.bing.com", multipartBody);
(Visited 1,076 times, 2 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.