OKhttp3实现multipart/form-data上传

**

OKhttp3实现multipart/form-data上传 需要权限:

**



file[]数组,多文件上传

public void uploadFiles(List list) {

        OkHttpClient httpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型,类型为八位字节流
        //RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        builder.addFormDataPart("t", "123");//传递键值对参数
        builder.addFormDataPart("sk", "379fe678ddc271c677b642c6c0d801db");
        builder.addFormDataPart("userId", userId);
        builder.addFormDataPart("postBarId", "");
        builder.addFormDataPart("token", "");
        builder.addFormDataPart("title", "123");
        builder.addFormDataPart("content", "123");

        for (int i = 0; i < list.size(); i++) {
            File file = new File(list.get(i));
            builder.addFormDataPart("picFiles", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));//文件名,请求体里的文件
        }

        Request request = new Request.Builder()
                .header("Authorization", "Bearer d3e63518-1ba7-4342-b94c-63c8b9b9046b")//添加请求头的身份认证Token
                .url(Config.update_PostBar)
                .post(builder.build())
                .build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG-失败:", e.toString() + "");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("TAG-成功:", string + "");

            }
        });
    }

file,单文件上传

public void uploadFile(String getPath,String url ) {
        File file = new File(getPath);//文件路径
        long size = file.length();//文件长度
        OkHttpClient httpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型,类型为八位字节流
        RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体

        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
            	 .addFormDataPart("id", 0 + "")//添加表单数据
            	.addFormDataPart("user", 1 + "")
                .addFormDataPart("file", file.getName(), requestBody)//文件名,请求体里的文件
                .build();

        Request request = new Request.Builder()
                .header("Authorization", "Bearer d3e63518-1ba7-4342-b94c-63c8b9b9046b")//添加请求头的身份认证Token
                .url(url)
                .post(multipartBody)
                .build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG-失败:", e.toString() + "");
            }

            @Override## 标题
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("TAG-成功:", string + "");
            }
        });
    }

上传JSON数据

private static void uploadingCallRecords() {
    new Thread() {
        @Override
        public void run() {
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject js = new JSONObject();
            //上传json,参数
            try {
                js.put("companyId", "1");
 
                js.put("id", "");
 
                js.put("phoneInNumber", "10086");
 
                js.put("phoneOutNumber","10086");
 
                js.put("phoneRecordAddress", "");
 
                js.put("phoneRingTime", "");
 
                js.put("phoneStartTime", "");
 
                js.put("phoneEndTime", "");
 
                js.put("phoneStatus", "0");
 
                js.put("phoneCallType","3");
 
                js.put("phoneClientType", 1);
 
                js.put("userId", "");
 
                js.put("uid", "");
 
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //申明给服务端传递一个json串
            //创建一个OkHttpClient对象
            OkHttpClient okHttpClient = new OkHttpClient();
            //创建一个RequestBody(参数1:数据类型 参数2传递的json串)
            //json为String类型的json数据
            RequestBody requestBody = RequestBody.create(JSON, String.valueOf(js));
            //创建一个请求对象
            Request request = new Request.Builder()
                    .addHeader("Authorization", "这里放你的token")//身份验证的Token
                    .url("这里放你的url")//上传接口
                    .post(requestBody)
                    .build();
 
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("TAG上传失败返回:", e.toString() + "");
                }
 
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String string = response.body().string();
                    Log.e("TAG上传成功返回:", string + "");
                }
            });
        }
    }.start();
}

你可能感兴趣的:(Android)