91.android 简单的通过okhttp(MultipartBody)来进行文件上传+Okhttp上传JSON数据

//第一步 在AndroidManifest.xml里先加权限,需要网络权限和读取的权限:


 //第二步 6.0以上得加动态权限,这都是为上传前做准备,得先读取文件:

//我用的是一个动态权限申请第三方的依赖:

compile 'com.lovedise:permissiongen:0.0.6'

//然后在Activity里开始申请:

private void permissiongen() {
    //处理需要动态申请的权限
    PermissionGen.with(MainActivity.this)
            .addRequestCode(200)
            .permissions(Manifest.permission.READ_EXTERNAL_STORAGE)
            .request();
}

//申请权限结果的返回
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
}

//权限申请成功
@PermissionSuccess(requestCode = 200)
public void doSomething() {
    //在这个方法中做一些权限申请成功的事情
    Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();
}

//申请失败
@PermissionFail(requestCode = 200)
public void doFailSomething() {
    Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
}

//然后在onCreate()方法里调用一下就行:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    permissiongen();
}

 

//第三步 上传之前先导入okhttp的依赖,再开始上传:

//okhttp依赖:

compile 'com.squareup.okhttp3:okhttp:3.9.1'

//开始上传,上传方法:

 

public void uploadFile() {
    File file = new File("/storage/emulated/0/song/10086电话录音2018-11-21-21-58-18.amr");//我的文件路径,需要改你自己的
    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("chunk", 0 + "")//添加表单数据
            .addFormDataPart("chunks", 1 + "")
            .addFormDataPart("fileMd5", "12312")
            .addFormDataPart("chunkSize", 1 + "")
            .addFormDataPart("name", file.getName())
            .addFormDataPart("size", size + "")
            .addFormDataPart("uid", "456")
            .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 + "");
        }
    });
}

//好了,在哪里需要上传就调用 uploadFile()方法就行了

 

//Okhttp上传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");//0未接通,1接通

                js.put("phoneCallType","3");//3外呼,4接入

                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();
}

//-----------------------------------------------------------------------完--------------------------------------------------------------------------- 

你可能感兴趣的:(okhttp,android)