Android使用OkHttp(Basic认证)并上传文件

 /**
     *
     * @param path 上传文件本地地址
     * @param url 上传地址
     * @param username 账号
     * @param password 密码
     */
    public static void upload(String path,String url,String username,String password){
        String name = path.substring(path.lastIndexOf("/") + 1);
        final String basic = Credentials.basic(username, password);
        RequestBody body = RequestBody.create(MediaType.parse("image/jpeg"), path);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                //参数分别为:文件,文件名字,文件类型与路径
                .addFormDataPart("file", name, body)//文件名
                .build();
        OkHttpClient client = new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        return response.request().newBuilder().header("Authorization", basic).build();
                    }
                })
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("连接失败", "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "连接成功:" + response);
            }
        });

    }
发布了15 篇原创文章 · 获赞 5 · 访问量 360

猜你喜欢

转载自blog.csdn.net/weixin_44059750/article/details/105099565
今日推荐