文件上传(OkHttpClient)

   private String fileName;
  fileName = Environment.getExternalStorageDirectory().getPath() + "/webview_jietu.jpg";
private void imageUpload(String filename) {//文件路径  
        file = new File(filename);
        if (file == null || !file.exists()) {
            LogUtil.e(TAG, "screencap is failed");
            return;
        }
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .build();
        MediaType type = MediaType.parse("application/octet-stream");//"text/xml;charset=utf-8"
        RequestBody fileBody = RequestBody.create(type, file);
        RequestBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.ALTERNATIVE)
//                .addPart(Headers.of(
//                        "Content-Disposition",
//                        "form-data; name=\"screenShotimg\"; filename=" + file.getName())
//                        , fileBody)

                .addFormDataPart("file", file.getName(), fileBody)
                .addFormDataPart("mac", MyApplication.getSettingManager().getMac())
                .build();
        Request request = new Request.Builder()
                .url(UrlsUtil.getUrl("/api/v2/match"))
                .addHeader("User-Agent", "android")
                .header("Content-Type", "text/html; charset=utf-8;")
                .addHeader("Mac", MyApplication.getSettingManager().getMac())
                .addHeader("Token", MD5Util.MD5(MyApplication.getSettingManager().getMac().toUpperCase() + "BOE_SCREENOS").toUpperCase())
                .post(multipartBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    Log.d(TAG, "上传成功");
//                    cameraFacenet("2");
                } else {
                    Log.d(TAG, "上传失败");
                }

            }
        });

    }

你可能感兴趣的:(文件上传(OkHttpClient))