首先得到展示上传头像和获取用户信息的接口:
把模拟器中的图片上传上去后并下载下来,在activity中显示:
首先需要的依赖:
compile 'com.squareup.okhttp3:okhttp:3.10.0' implementation files('libs/gson-2.6.2.jar') compile 'com.github.bumptech.glide:glide:3.7.0'Activity_main.xml中:
xml version="1.0" encoding="utf-8"?>MainActivity中:xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.zym.okhttpupfile.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="上传" android:onClick="upFile"/> android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/image"/>
package com.example.zym.okhttpupfile; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.gson.Gson; import java.io.File; import java.io.IOException; import java.util.HashMap; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class MainActivity extends AppCompatActivity { String url = "https://www.zhaoapi.cn/file/upload"; private ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = findViewById(R.id.image); } public void upFile(View view) { File file = new File(Environment.getExternalStorageDirectory()+"/Pictures", "xxoo_1.png"); HashMapOkHttpUtils中:, String> params = new HashMap<>(); params.put("uid","5201"); OkhtttpUtils.upImage(url, file, "xx.png", params, 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 { if (response.isSuccessful()){ //请求用户的信息 OkhtttpUtils.doGet("https://www.zhaoapi.cn/user/getUserInfo?uid=5201", new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //如果是成功的话,我就可以获得头像图片的地址 String json = response.body().string(); //获得用户的信息,并进行解析 UserBean userBean = new Gson().fromJson(json, UserBean.class); Log.e("++++++",userBean.getMsg()); //图片的地址 final String iconURl = userBean.getData().getIcon(); //要放在主线程 runOnUiThread(new Runnable() { @Override public void run() { Glide.with(MainActivity.this).load(iconURl).into(image); } }); } }); } } }); } }
package com.example.zym.okhttpupfile; import android.os.Environment; import java.io.File; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import static android.R.string.ok; import static android.os.Build.VERSION_CODES.M; /** * Created by Administrator on 2018/3/8. */ public class OkhtttpUtils { //单例模式,把构造方法进行私有化 // private OkhtttpUtils(){}; static OkHttpClient client; public static OkHttpClient getInstance(){ if (client==null) { //更加安全 synchronized (OkhtttpUtils.class) { //缓存的地方 mnt/sdcard File file = new File(Environment.getExternalStorageDirectory(), "cache11"); client = new OkHttpClient().newBuilder() .readTimeout(3000, TimeUnit.SECONDS) //设置读取超时时间 .connectTimeout(3000, TimeUnit.SECONDS) //设置连接的超时时间 .cache(new Cache(file, 10 * 1024)) .build(); } } return client; } /** * get请求 * Callback 是一个接口 */ public static void doGet(String url, Callback callback){ //1:拿到okhttpclient 对像 OkHttpClient client = getInstance(); //2:进行请求的操作 Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(callback); } //post请求 public static void doPost(String url, MapUserBean中:,String> parms,Callback callback){ //得到客户端的对像 OkHttpClient client = getInstance(); //不是FormBody,而是一个Builder FormBody.Builder body = new FormBody.Builder(); //key value for (String key:parms.keySet()){ //value的值 body.add(key,parms.get(key)); } Request request = new Request.Builder() .url(url) .post(body.build()) .build(); client.newCall(request).enqueue(callback); } //url File(图片) 参数 Callback public static void upImage(String url,File file,String fileName,Map ,String> params,Callback callback){ OkHttpClient client = getInstance(); //requestBody的实现类 Formbody MultipartBody.Builder builder = new MultipartBody.Builder(); if (params!=null){ for (String key :params.keySet()){ builder.addFormDataPart(key,params.get(key)); } } //设置类型 builder.setType(MultipartBody.FORM); builder.addFormDataPart("file",fileName,RequestBody.create(MediaType.parse("application/octet-stream"),file)); Request request = new Request.Builder() .url(url) .post(builder.build()) .build(); client.newCall(request).enqueue(callback); } }
package com.example.zym.okhttpupfile; /** * Created by Administrator on 2018/3/20. */ public class UserBean { /** * code : 0 * data : {"appkey":"3513ed45f14905eb","appsecret":"02834A8A5D9E7B50F65A02D302F9EAC5","createtime":"2017-11-29T13:21:42","fans":0,"follow":0,"icon":"https://www.zhaoapi.cn/images/1521556817701aa.jpg","mobile":"13775559134","password":"94E3FA7E637B0803B4034D7B1B165B83","uid":3010,"username":"13775559134"} * msg : 获取用户信息成功 */ private String code; private DataBean data; private String msg; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public static class DataBean { /** * appkey : 3513ed45f14905eb * appsecret : 02834A8A5D9E7B50F65A02D302F9EAC5 * createtime : 2017-11-29T13:21:42 * fans : 0 * follow : 0 * icon : https://www.zhaoapi.cn/images/1521556817701aa.jpg * mobile : 13775559134 * password : 94E3FA7E637B0803B4034D7B1B165B83 * uid : 3010 * username : 13775559134 */ private String appkey; private String appsecret; private String createtime; private int fans; private int follow; private String icon; private String mobile; private String password; private int uid; private String username; public String getAppkey() { return appkey; } public void setAppkey(String appkey) { this.appkey = appkey; } public String getAppsecret() { return appsecret; } public void setAppsecret(String appsecret) { this.appsecret = appsecret; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public int getFans() { return fans; } public void setFans(int fans) { this.fans = fans; } public int getFollow() { return follow; } public void setFollow(int follow) { this.follow = follow; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } }