上传图片 下载图片

本文介绍了一个使用OkHttp库在Android应用中实现图片上传和下载的示例。通过创建OkHttpClient实例并配置超时时间,文章展示了如何构建Request对象来发送POST请求上传图片,以及GET请求下载图片,并在主线程中更新UI显示下载的图片。
摘要由CSDN通过智能技术生成
package com.example.okhttpzhaopian;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button upLoaDing;
    private Button downLoad;
    private String path;
    private ImageView image;
    private String upLoaDingPaht;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        path = "https://10.url.cn/eth/ajNVdqHZLLAxibwnrOxXSzIxA76ichutwMCcOpA45xjiapneMZsib7eY4wUxF6XDmL2FmZEVYsf86iaw/";
        upLoaDingPaht = "https://www.718shop.com/sell/sell.m.picture.upload.do";
    }

    private void initView() {
        upLoaDing = (Button) findViewById(R.id.upLoaDing);
        downLoad = (Button) findViewById(R.id.downLoad);

        upLoaDing.setOnClickListener(this);
        downLoad.setOnClickListener(this);
        image = (ImageView) findViewById(R.id.image);
        image.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.upLoaDing:
                setUpLoaDing();
                break;
            case R.id.downLoad:
                setDownLoad();
                break;
        }
    }

    private void setUpLoaDing() {
        //获得本地的图片
        File file = new File(Environment.getExternalStorageDirectory()+"/Download", "start.jpg");


        RequestBody body = RequestBody.create(MediaType.parse("application/octet_stream"),file);

        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "start.jpg", body)
                .build();

        final Request request = new Request.Builder()
                .url(upLoaDingPaht)
                .post(multipartBody)
                .build();

        new OkHttpClient.Builder()
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("zzh", "onResponse: "+response.body().string() );
            }
        });
    }


    //上传图片


    //设置下载图片的操作票
    private void setDownLoad() {

        final Request request = new Request.Builder()
                .url(path)
                .build();

        new OkHttpClient.Builder()
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException 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 {
                final byte[] bytes = response.body().bytes();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        image.setImageBitmap(bitmap);
                        File file = new File(Environment.getExternalStorageDirectory(), "diyi.png");
                        try {
                            FileOutputStream fileOutputStream = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });


    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值