File upload with okhttp

前端 未结 4 1612
孤城傲影
孤城傲影 2020-12-06 02:54

Im finishing this project which is using okhttp for communication with a webservice.

All is going fine for regular GETs and POSTs, but I\'m not being able to properl

4条回答
  •  佛祖请我去吃肉
    2020-12-06 03:16

    I just changed addFormDataPart instead addPart and Finally solved My Problem Using following code:

      /**
         * Upload Image
         *
         * @param memberId
         * @param sourceImageFile
         * @return
         */
        public static JSONObject uploadImage(String memberId, String sourceImageFile) {
    
            try {
                File sourceFile = new File(sourceImageFile);
    
                Log.d(TAG, "File...::::" + sourceFile + " : " + sourceFile.exists());
    
                final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    
                RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addFormDataPart("member_id", memberId)
                        .addFormDataPart("file", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                        .build();
    
                Request request = new Request.Builder()
                        .url(URL_UPLOAD_IMAGE)
                        .post(requestBody)
                        .build();
    
                OkHttpClient client = new OkHttpClient();
                Response response = client.newCall(request).execute();
                return new JSONObject(response.body().string());
    
            } catch (UnknownHostException | UnsupportedEncodingException e) {
                Log.e(TAG, "Error: " + e.getLocalizedMessage());
            } catch (Exception e) {
                Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
            }
            return null;
        }
    

提交回复
热议问题