美文网首页
OkHttp上传图片

OkHttp上传图片

作者: 好学人 | 来源:发表于2019-07-09 23:29 被阅读0次

    添加权限

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    添加依赖

    implementation("com.squareup.okhttp3:okhttp:3.12.3")
    

    示例代码

    /**
     * Okhttp上传图片(流)
     */
    private void okHttpUploadImage() {
        // 创建 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder().build();
        // 要上传的文件
        File file = new File("/storage/emulated/0/Download/timg-4.jpg");
        MediaType mediaType = MediaType.parse("image/jpeg");
        // 把文件封装进请求体
        RequestBody fileBody = RequestBody.create(mediaType, file);
        // MultipartBody 上传文件专用的请求体
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM) // 表单类型(必填)
                .addFormDataPart("smfile", file.getName(), fileBody)
                .build();
        Request request = new Request.Builder()
                .url("https://sm.ms/api/upload")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0")
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
    
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    System.out.println(response.body().string());
                } else {
                    System.out.println(response.code());
                }
            }
    
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
        });
    }
    

    相关文章

      网友评论

          本文标题:OkHttp上传图片

          本文链接:https://www.haomeiwen.com/subject/mzyqkctx.html