Okhttp3上傳引數、檔案和同時上傳
阿新 • • 發佈:2019-02-08
OkHttpClient client=new OkHttpClient(); //一種:引數請求體 FormBody paramsBody=new FormBody.Builder() .add("id",currentPlan.getPlanId()+"") .add("name",currentPlan.getName()) .add("volume",currentPlan.getVolume()) .add("type",currentPlan.getType()+"") .add("mode",currentPlan.getMode()+"") .build(); //二種:檔案請求體 MediaType type=MediaType.parse("application/octet-stream");//"text/xml;charset=utf-8" File file=new File("/data/data/com.example.company/files/plan/plans.xml"); RequestBody fileBody=RequestBody.create(type,file); //三種:混合引數和檔案請求 RequestBody multipartBody = new MultipartBody.Builder() .setType(MultipartBody.ALTERNATIVE)
//一樣的效果 .addPart(Headers.of( "Content-Disposition", "form-data; name=\"params\"") ,paramsBody) .addPart(Headers.of( "Content-Disposition", "form-data; name=\"file\"; filename=\"plans.xml\"") , fileBody) //一樣的效果/*.addFormDataPart("id",currentPlan.getPlanId()+"") .addFormDataPart("name",currentPlan.getName()) .addFormDataPart("volume",currentPlan.getVolume()) .addFormDataPart("type",currentPlan.getType()+"") .addFormDataPart("mode",currentPlan.getMode()+"") .addFormDataPart("params","plans.xml",fileBody)*/ .build(); Request request=new Request.Builder().url("http://192.168.1.121:8080/Server/Service") .addHeader("User-Agent","android") .header("Content-Type","text/html; charset=utf-8;") .post(multipartBody)//傳引數、檔案或者混合,改一下就行請求體就行 .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { Log.i("xxx","1、連線的訊息"+response.message()); if(response.isSuccessful()){ Log.i("xxx","2、連線成功獲取的內容"+response.body().string()); } } });