使用 OkHttp上传一个图片

使用OkHttp 上传图片一定要使用 post 请求方式 这里使用的是异步的post 请求方式 还是用了HttpLoggingInterceptor 日志监听
权限



导入的依赖

implementation 'com.squareup.okhttp3:okhttp:3.12.0'/*这是使用okhttp 的依赖*/
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'/*这是添加日志监听的依赖*/

具体代码

public class OkUtils {

    private OkHttpClient okHttpClient;

    public OkUtils() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(20,TimeUnit.SECONDS)
                .readTimeout(20,TimeUnit.SECONDS)
                .callTimeout(20,TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .build();
    }

    public static OkUtils getInstance(){
        return OkHolder.okUtils;
    }

    static class OkHolder{
        private static final OkUtils okUtils = new OkUtils();
    }
 	public void upLoadImage(String murl,String uid,Callback callback){
        File file = new File(Environment.getExternalStorageDirectory()+"/DCIM/zuiyou/414606767.jpg");// 后面的是要上传图片的地址
        MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("uid",uid)
                .addFormDataPart("file","414606767.jpg",RequestBody.create(MediaType.parse("image/jpg"),file));
        RequestBody body1 = body.build();
        Request request = new Request.Builder().url(murl).post(body1).build();
        okHttpClient.newCall(request).enqueue(callback);
    }
}

Mainactivity 中的代码

OkUtils.getInstance().upLoadImage(mUrl, uid, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("onFailure",e.getMessage()+"");
                        //强制在主线程中刷新,不推荐使用,太消耗内存
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.e("onResponse",response.body().string()+"");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });

你可能感兴趣的:(安卓学习)