使用Okhttp上传图片

写项目的时候接触了上传图片这个模块。第一次使用OKhttputils上传图片时发现有时候上传成功,有时候失败报500错误,我纠结了一天,用postman测试接口是没有问题的,最后换回原生的okhttp框架去写。后来发现可能是之前的OKhttputils版本太低了导致的(2.6.2),现在用的Okhttp版本是(3.2.0

private static final String TAG = "MainActivity";
private Button btn_up;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn_up = (Button) findViewById(R.id.btn_up);
    btn_up.setOnClickListener(this);
}



private void upImage() {
    OkHttpClient mOkHttpClent = new OkHttpClient();
    File file = new File(Environment.getExternalStorageDirectory()+"/HeadPortrait.jpg");
    MultipartBody.Builder builder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("img", "HeadPortrait.jpg",
                    RequestBody.create(MediaType.parse("image/png"), file));

    RequestBody requestBody = builder.build();

    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Call call = mOkHttpClent.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "onFailure: "+e );
            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(TAG, "成功"+response);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
    });

}

@Override
public void onClick(View v) {
    Log.e(TAG, "onClick: " );
    new Thread(new Runnable() {
        @Override
        public void run() {
            upImage();
        }
    }).start();
}

点击下载源码

你可能感兴趣的:(安卓移动开发)