新建一个OKHttp的通用类
package com.example.app.util;
import android.os.Handler;
import android.os.Looper;
import org.json.JSONException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by fan on 2016/11/9.
*/
public class OKHttp {
/**
* 静态实例
*/
private static OKHttp sOkHttpManager;
/**
* okhttpclient实例
*/
private OkHttpClient mClient;
/**
* 因为我们请求数据一般都是子线程中请求,在这里我们使用了handler
*/
private Handler mHandler;
/**
* 构造方法
*/
private OKHttp() {
// mClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).build();
mClient = new OkHttpClient();
/**
* 在这里直接设置连接超时.读取超时,写入超时
*/
OkHttpClient.Builder builder = mClient.newBuilder();
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.readTimeout(10, TimeUnit.SECONDS);
builder.writeTimeout(10, TimeUnit.SECONDS);
mClient = builder.build();
/**
* 如果是用的3.0之前的版本 使用以下直接设置连接超时.读取超时,写入超时
*/
//client.setConnectTimeout(10, TimeUnit.SECONDS);
//client.setWriteTimeout(10, TimeUnit.SECONDS);
//client.setReadTimeout(30, TimeUnit.SECONDS);
/**
* 初始化handler
*/
mHandler = new Handler(Looper.getMainLooper());
}
/**
* 单例模式 获取OkHttp实例
*
* @return
*/
public static OKHttp getInstance() {
if (sOkHttpManager == null) {
sOkHttpManager = new OKHttp();
}
return sOkHttpManager;
}
//-------------------------同步的方式请求数据--------------------------
/**
* 对外提供的get方法,同步的方式
*
* @param url 传入的地址
* @return
*/
public static Response getSync(String url) {
//通过获取到的实例来调用内部方法
return sOkHttpManager.inner_getSync(url);
}
/**
* GET方式请求的内部逻辑处理方式,同步的方式
*
* @param url
* @return
*/
private Response inner_getSync(String url) {
Request request = new Request.Builder().url(url).build();
Response response = null;
try {
//同步请求返回的是response对象
response = mClient.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* 对外提供的同步获取String的方法
*
* @param url
* @return
*/
public static String getSyncString(String url) {
return sOkHttpManager.inner_getSyncString(url);
}
/**
* 同步方法
*/
private String inner_getSyncString(String url) {
String result = null;
try {
/**
* 把取得到的结果转为字符串,这里最好用string()
*/
result = inner_getSync(url).body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//-------------------------异步的方式请求数据--------------------------
public static void getAsync(String url, DataCallBack callBack) {
getInstance().inner_getAsync(url, callBack);
}
/**
* 内部逻辑请求的方法
*
* @param url
* @param callBack
* @return
*/
private void inner_getAsync(String url, final DataCallBack callBack) {
final Request request = new Request.Builder().url(url).build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
deliverDataFailure(request, e, callBack);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = null;
try {
result = response.body().string();
} catch (IOException e) {
deliverDataFailure(request, e, callBack);
}
deliverDataSuccess(result, callBack);
}
});
}
/**
* 分发失败的时候调用
*
* @param request
* @param e
* @param callBack
*/
private void deliverDataFailure(final Request request, final IOException e, final DataCallBack callBack) {
/**
* 在这里使用异步处理
*/
mHandler.post(new Runnable() {
@Override
public void run() {
if (callBack != null) {
try {
callBack.requestFailure(request, e);
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}
});
}
/**
* 分发成功的时候调用
*
* @param result
* @param callBack
*/
private void deliverDataSuccess(final String result, final DataCallBack callBack) {
/**
* 在这里使用异步线程处理
*/
mHandler.post(new Runnable() {
@Override
public void run() {
if (callBack != null) {
try {
callBack.requestSuccess(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
/**
* 数据回调接口
*/
public interface DataCallBack {
void requestFailure(Request request, IOException e) throws JSONException;
void requestSuccess(String result) throws Exception;
}
//-------------------------提交表单--------------------------
public static void postAsync(String url, Map<String, String> params, DataCallBack callBack) {
getInstance().inner_postAsync(url, params, callBack);
}
private void inner_postAsync(String url, Map<String, String> params, final DataCallBack callBack) {
RequestBody requestBody = null;
if (params == null) {
params = new HashMap<>();
}
/**
* 如果是3.0之前版本的,构建表单数据是下面的一句
*/
//FormEncodingBuilder builder = new FormEncodingBuilder();
/**
* 3.0之后版本
*/
FormBody.Builder builder = new FormBody.Builder();
/**
* 在这对添加的参数进行遍历,map遍历有四种方式,如果想要了解的可以网上查找
*/
for (Map.Entry<String, String> map : params.entrySet()) {
String key = map.getKey().toString();
String value = null;
/**
* 判断值是否是空的
*/
if (map.getValue() == null) {
value = "";
} else {
value = map.getValue();
}
/**
* 把key和value添加到formbody中
*/
builder.add(key, value);
}
requestBody = builder.build();
//结果返回
// 请求对象
final Request request = new Request.Builder().url(url).post(requestBody).build();
mClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
deliverDataFailure(request, e, callBack);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
deliverDataSuccess(result, callBack);
}
});
}
}
private Button imgbtn;//这里写自己的控件即可
private ImageView img;//显示图片的控件,别忘了find
imgbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
} else {
intent.setAction(Intent.ACTION_GET_CONTENT);
}
intent.setType("image/*");
startActivityForResult(intent, 1000);//打开相册
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {//相册的调用回调
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000) {//判断是否是我们通过photo()发起的
if (resultCode == Activity.RESULT_OK && null != data) {
Uri uri = data.getData();
ContentResolver cr = getActivity().getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));//获取位图
//将位图转为字节数组后再转为base64
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
img.setImageBitmap(bitmap);
//发起网络请求,传入base64数据
setImgByStr(Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 上传头像
* @param imgStr
*/
public void setImgByStr(String imgStr) {
String url = SERVER+"/api_upload.do";
HashMap<String, String> params = new HashMap<String, String>();
params.put("files", imgStr);
OKHttp.postAsync(url, params, new OKHttp.DataCallBack() {
@Override
public void requestFailure(Request request, IOException e) throws JSONException {
Log.i("上传失败", "失败" + request.toString() + e.toString());
Toast.makeText(getActivity(),"上传失败", Toast.LENGTH_SHORT).show();
}
@Override
public void requestSuccess(String result) throws Exception {
JSONObject json = new JSONObject(result);
Log.i("上传成功", result);
Toast.makeText(getActivity(),json.getString("msg"), Toast.LENGTH_SHORT).show();
}
});
}
- 本文标题: 用OkHttp3从相册上传图片
- 文章分类:【Android】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.