如何使用okHttp发布文件和Json数据

时间:2018-06-21 17:32:46

标签: android okhttp3

在下面的代码中,我尝试使用OkHttpClient一起发送文件和JSON格式的数据,但没有收到任何响应。看来问题出在MultipartBody上,以下是JAVA和PHP代码,在此先感谢

@Override
protected void onHandleIntent(@Nullable Intent intent) {


    Products mProducts= null;
    try {
        mProducts = intent.getParcelableExtra(INTENT_UPLOAD_PRODUCT);
        imagesUri=new ArrayList<>(intent.getExtras().getStringArrayList(INTENT_UPLOAD_PRODUCT_IMAGES));
    } catch (Exception mE) {
        mE.printStackTrace();
    }



    MediaType jsonType=MediaType.parse("application/json; charset=utf-8");
    MediaType bitmapType=MediaType.parse("image/jpg");

    File mFile1=new File(Uri.parse(imagesUri.get(0)).getPath());
    File mFile2=new File(Uri.parse(imagesUri.get(1)).getPath());

    OkHttpClient mOkHttpClient=new OkHttpClient();
    Request.Builder mBuilder=new Request.Builder();

    Gson gson = new Gson();
    String productAsJson=gson.toJson(mProducts);


    MultipartBody.Builder multi=new MultipartBody.Builder().setType(MultipartBody.FORM);
    multi.addPart(RequestBody.create(jsonType,productAsJson));
    multi.addFormDataPart("file",mProducts.getImage1(),RequestBody.create(bitmapType,mFile1));

    try {


        RequestBody mRequestBody=multi.build();
        Request mRequest=mBuilder.post(mRequestBody).url(Main.UPLOAD_PRODUCT_URL).build();
        Response mResponse =mOkHttpClient.newCall(mRequest).execute();
        String result=mResponse.body().string();

        Log.v(TAG,"res "+result);

    } catch (IOException mE) {
        mE.printStackTrace();
    }

}

和PHP

 $res=array();
 if(isset($_FILES['file'])){            
 //move_uploaded_file($_FILES['file'], UPLOAD_PATH .$_FILES['file']['name']);
 $res['file_status']=true;      
 }else {$res['file_status']=false;}
 $data = file_get_contents('php://input');
 $arr = json_decode($data,true);    
 $res['data']=$arr['name'];
 echo json_encode($res);

0 个答案:

没有答案