Search code examples
phpandroidokhttp

okhttp3 Null Respone uploading file


Hi I am trying to upload a jpg file using okhttp3's multipart request to a php server. The script checks for $_FILES["image1"] and works correctly from html form. When using the below code I get a null response from server.

If I remove the last addFormDataPart that contains the file upload part, I get a response from server that image1 is not set.

Edit* I have found that boolean b = files.get(0).isFile(); returns false for files stored on my mobile device and true for those on dropbox. Dropbox files return correct response file on phone still return null http response.

Any suggestions?

public AsyncHttpPost(String id, String password, List<File> files, OnTaskComplete listener ) {
    MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpg");
    MultipartBody.Builder  builder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(ResponseDTO.TAG_ID, String.valueOf(id))
            .addFormDataPart(ResponseDTO.TAG_PASSWORD, password)
            .addFormDataPart("image1", "Test.jpg", RequestBody.create(MEDIA_TYPE_JPG, files.get(0)));

    mRequestBody = builder.build();
    mListener = listener;
}

public AsyncHttpPost() {
}

public void setListener(OnTaskComplete listener) {
    mListener = listener;
}

@Override
protected String doInBackground(String... params) {
    String result = "";

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(params[0])
            .post(mRequestBody)
            .build();

    Response response  = null;
    try {
        response = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        if (response != null) {
            result = response.body().string();
        } else {
            result = "null";
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

Solution

  • when using the URI path isFile() returned false. So I had to create file using path as below. This then lead to a null response after a few seconds so i also updated timeout values for my http client

    File f = new File(uri.getPath()); //didnt work
    File f = new File("/storage/emulated/0/DCIM/Camera/Test.jpg");
    
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(300, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();