1

In my android app I am using okhttp:3.10.0 to create a httpclient to make a request to google drive (REST V3) api. I want to create a folder in users google drive. I read google documentation to create a folder. This documentation suggest to have something like this

File fileMetadata = new File();
fileMetadata.setName("Invoices");
fileMetadata.setMimeType("application/vnd.google-apps.folder");

I went through this question as well. I am making the okhttpclient like this

OkHttpClient client = new OkHttpClient();
                        RequestBody body = ????????
                        Request request = new Request.Builder()
                                .url("https://www.googleapis.com/drive/v3/files")
                                .addHeader("Authorization", String.format("Bearer %s", tokens[0]))
                                .post(body)
                                .build();

                        try {
                            Response response = client.newCall(request).execute();
                            String jsonBody = response.body().string();
                            Log.i(LOG_TAG, String.format("User Info Response %s", jsonBody));
                            return new JSONObject(jsonBody);
                        } catch (Exception exception) {
                            Log.w(LOG_TAG, exception);
                        }
                        return null;

I am trying to use a json object but it is not converting to request body because it can not resolve companion

import okhttp3.MediaType.Companion.toMediaTypeOrNull;
import okhttp3.RequestBody.Companion.toRequestBody;

JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("title", "Ancd test");
                            jsonObject.put("mimeType", "application/vnd.google-apps.folder");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        String body = jsonObject.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull());

Now I am not sure how to add that meta data in request body. Anyone knows how to do this?

Karan
  • 752
  • 2
  • 13
  • 34

1 Answers1

2
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");                
RequestBody body = RequestBody.create(jsonObject.toString(), mediaType);
  • sorry my bad then; typically I would expect to see more depth in answers rather than just the code itself; it is OK as soon as everyone is happy about it! – feanor07 Jul 09 '20 at 20:09