@Override
public void onError(Request request, IOException e)
{
e.printStackTrace();
}
@Override
public void onResponse(String result)
{
}
},//
file,//
“mFile”,//
new OkHttpClientManager.Param[]{
new OkHttpClientManager.Param(“username”, “zhy”),
new OkHttpClientManager.Param(“password”, “123”)}
);
键值对没什么说的,参数3为file,参数4为file对应的name,这个name不是文件的名字;
对应于http中的
<input type="file" name="mFile" >
对应的是name后面的值,即mFile.
- 文件下载
对于文件下载,提供url,目标dir,callback即可。
OkHttpClientManager.downloadAsyn(
“http://192.168.1.103:8080/okHttpServer/files/messenger_01.png”,
Environment.getExternalStorageDirectory().getAbsolutePath(),
new OkHttpClientManager.ResultCallback()
{
@Override
public void onError(Request request, IOException e)
{
}
@Override
public void onResponse(String response)
{
//文件下载成功,这里回调的reponse为文件的absolutePath
}
});
- 展示图片
展示图片,我们希望提供一个url和一个imageview,如果下载成功,直接帮我们设置上即可。
OkHttpClientManager.displayImage(mImageView,
“http://images.csdn.net/20150817/1.jpg”);
内部会自动根据imageview的大小自动对图片进行合适的压缩。虽然,这里可能不适合一次性加载大量图片的场景,但是对于app中偶尔有几个图片的加载,还是可用的。
四、整合Gson
很多人提出项目中使用时,服务端返回的是Json字符串,希望客户端回调可以直接拿到对象,于是整合进入了Gson,完善该功能。
(一)直接回调对象
例如现在有个User实体类:
package com.zhy.utils.http.okhttp;
public class User {
public String username ;
public String password ;
public User() {
// TODO Auto-generated constructor stub
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString()
{
return “User{” +
“username='” + username + ‘’’ +
“, password='” + password + ‘’’ +
‘}’;
}
}
服务端返回:
{“username”:“zhy”,“password”:“123”}
客户端可以如下方式调用:
OkHttpClientManager.getAsyn(“http://192.168.56.1:8080/okHttpServer/user!getUser”,
new OkHttpClientManager.ResultCallback()
{
@Override
public void onError(Request request, Exception e)
{
e.printStackTrace();
}
@Override
public void onResponse(User user)
{
mTv.setText(u.toString());//UI线程
}
});
我们传入泛型User,在onResponse里面直接回调User对象。
这里特别要注意的事,如果在json字符串->实体对象
过程中发生错误,程序不会崩溃,onError
方法会被回调。
注意:这里做了少许的更新,接口命名从StringCallback
修改为ResultCallback
。接口中的onFailure
方法修改为onError
。
(二) 回调对象集合
依然是上述的User类,服务端返回
[{“username”:“zhy”,“password”:“123”},{“username”:“lmj”,“password”:“12345”}]
则客户端可以如下调用:
OkHttpClientManager.getAsyn(“http://192.168.56.1:8080/okHttpServer/user!getUsers”,
new OkHttpClientManager.ResultCallback<List>()
{
@Override
public void onError(Request request, Exception e)
{
e.printStackTrace();
}
@Override
public void onResponse(List us)
{
Log.e(“TAG”, us.size() + “”);
mTv.setText(us.get(1).toString());
}
});
唯一的区别,就是泛型变为List<User>
,ok , 如果发现bug或者有任何意见欢迎留言。
源码
ok,基本介绍完了,对于封装的代码其实也很简单,我就直接贴出来了,因为也没什么好介绍的,如果你看完上面的用法,肯定可以看懂:
package com.zhy.utils.http.okhttp;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;
import com.google.gson.Gson;
import com.google.gson.internal. G s o n Gson GsonTypes;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
- Created by zhy on 15/8/17.
*/
public class OkHttpClientManager
{
private static OkHttpClientManager mInstance;
private OkHttpClient mOkHttpClient;
private Handler mDelivery;
private Gson mGson;
private static final String TAG = “OkHttpClientManager”;
private OkHttpClientManager()
{
mOkHttpClient = new OkHttpClient();
//cookie enabled
mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
mDelivery = new Handler(Looper.getMainLooper());
mGson = new Gson();
}
public static OkHttpClientManager getInstance()
{
if (mInstance == null)
{
synchronized (OkHttpClientManager.class)
{
if (mInstance == null)
{
mInstance = new OkHttpClientManager();
}
}
}
return mInstance;
}
/**
-
同步的Get请求
-
@param url
-
@return Response
*/
private Response _getAsyn(String url) throws IOException
{
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
Response execute = call.execute();
return execute;
}
/**
-
同步的Get请求
-
@param url
-
@return 字符串
*/
private String _getAsString(String url) throws IOException
{
Response execute = _getAsyn(url);
return execute.body().string();
}
/**
-
异步的get请求
-
@param url
-
@param callback
*/
private void _getAsyn(String url, final ResultCallback callback)
{
final Request request = new Request.Builder()
.url(url)
.build();
deliveryResult(callback, request);
}
/**
-
同步的Post请求
-
@param url
-
@param params post的参数
-
@return
*/
private Response _post(String url, Param… params) throws IOException
{
Request request = buildPostRequest(url, params);
Response response = mOkHttpClient.newCall(request).execute();
return response;
}
/**
-
同步的Post请求
-
@param url
-
@param params post的参数
-
@return 字符串
*/
private String _postAsString(String url, Param… params) throws IOException
{
Response response = _post(url, params);
return response.body().string();
}
/**
-
异步的post请求
-
@param url
-
@param callback
-
@param params
*/
private void _postAsyn(String url, final ResultCallback callback, Param… params)
{
Request request = buildPostRequest(url, params);
deliveryResult(callback, request);
}
/**
-
异步的post请求
-
@param url
-
@param callback
-
@param params
*/
private void _postAsyn(String url, final ResultCallback callback, Map<String, String> params)
{
Param[] paramsArr = map2Params(params);
Request request = buildPostRequest(url, paramsArr);
deliveryResult(callback, request);
}
/**
-
同步基于post的文件上传
-
@param params
-
@return
*/
private Response _post(String url, File[] files, String[] fileKeys, Param… params) throws IOException
{
Request request = buildMultipartFormRequest(url, files, fileKeys, params);
return mOkHttpClient.newCall(request).execute();
}
private Response _post(String url, File file, String fileKey) throws IOException
{
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
return mOkHttpClient.newCall(request).execute();
}
private Response _post(String url, File file, String fileKey, Param… params) throws IOException
{
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
return mOkHttpClient.newCall(request).execute();
}
/**
-
异步基于post的文件上传
-
@param url
-
@param callback
-
@param files
-
@param fileKeys
-
@throws IOException
*/
private void _postAsyn(String url, ResultCallback callback, File[] files, String[] fileKeys, Param… params) throws IOException
{
Request request = buildMultipartFormRequest(url, files, fileKeys, params);
deliveryResult(callback, request);
}
/**
-
异步基于post的文件上传,单文件不带参数上传
-
@param url
-
@param callback
-
@param file
-
@param fileKey
-
@throws IOException
*/
private void _postAsyn(String url, ResultCallback callback, File file, String fileKey) throws IOException
{
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
deliveryResult(callback, request);
}
/**
-
异步基于post的文件上传,单文件且携带其他form参数上传
-
@param url
-
@param callback
-
@param file
-
@param fileKey
-
@param params
-
@throws IOException
*/
private void _postAsyn(String url, ResultCallback callback, File file, String fileKey, Param… params) throws IOException
{
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
deliveryResult(callback, request);
}
/**
-
异步下载文件
-
@param url
-
@param destFileDir 本地文件存储的文件夹
-
@param callback
*/
private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback)
{
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(final Request request, final IOException e)
{
sendFailedStringCallback(request, e, callback);
}
@Override
public void onResponse(Response response)
{
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try
{
is = response.body().byteStream();
File file = new File(destFileDir, getFileName(url));
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1)
{
fos.write(buf, 0, len);
}
fos.flush();
//如果下载文件成功,第一个参数为文件的绝对路径
sendSuccessResultCallback(file.getAbsolutePath(), callback);
} catch (IOException e)
{
sendFailedStringCallback(response.request(), e, callback);
} finally
{
try
{
if (is != null) is.close();
} catch (IOException e)
{
}
try
{
if (fos != null) fos.close();
} catch (IOException e)
{
}
}
}
});
}
private String getFileName(String path)
{
int separatorIndex = path.lastIndexOf(“/”);
return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
}
/**
-
加载图片
-
@param view
-
@param url
-
@throws IOException
*/
private void _displayImage(final ImageView view, final String url, final int errorResId)
{
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(Request request, IOException e)
{
setErrorResId(view, errorResId);
}
@Override
public void onResponse(Response response)
{
InputStream is = null;
try
{
is = response.body().byteStream();
ImageUtils.ImageSize actualImageSize = ImageUtils.getImageSize(is);
ImageUtils.ImageSize imageViewSize = ImageUtils.getImageViewSize(view);
int inSampleSize = ImageUtils.calculateInSampleSize(actualImageSize, imageViewSize);
try
{
is.reset();
} catch (IOException e)
{
response = _getAsyn(url);
is = response.body().byteStream();
}
BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inJustDecodeBounds = false;
ops.inSampleSize = inSampleSize;
final Bitmap bm = BitmapFactory.decodeStream(is, null, ops);
mDelivery.post(new Runnable()
{
@Override
public void run()
{
view.setImageBitmap(bm);
}
});
} catch (Exception e)
{
setErrorResId(view, errorResId);
} finally
{
if (is != null) try
{
is.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
});
}
private void setErrorResId(final ImageView view, final int errorResId)
{
mDelivery.post(new Runnable()
{
@Override
public void run()
{
view.setImageResource(errorResId);
}
});
}
//*对外公布的方法
public static Response getAsyn(String url) throws IOException
{
return getInstance()._getAsyn(url);
}
public static String getAsString(String url) throws IOException
{
return getInstance()._getAsString(url);
}
public static void getAsyn(String url, ResultCallback callback)
{
getInstance()._getAsyn(url, callback);
}
public static Response post(String url, Param… params) throws IOException
{
return getInstance()._post(url, params);
}
public static String postAsString(String url, Param… params) throws IOException
{
return getInstance()._postAsString(url, params);
}
public static void postAsyn(String url, final ResultCallback callback, Param… params)
{
getInstance()._postAsyn(url, callback, params);
}
public static void postAsyn(String url, final ResultCallback callback, Map<String, String> params)
{
getInstance()._postAsyn(url, callback, params);
}
public static Response post(String url, File[] files, String[] fileKeys, Param… params) throws IOException
{
return getInstance()._post(url, files, fileKeys, params);
}
public static Response post(String url, File file, String fileKey) throws IOException
{
return getInstance()._post(url, file, fileKey);
}
public static Response post(String url, File file, String fileKey, Param… params) throws IOException
{
return getInstance()._post(url, file, fileKey, params);
}
public static void postAsyn(String url, ResultCallback callback, File[] files, String[] fileKeys, Param… params) throws IOException
{
getInstance()._postAsyn(url, callback, files, fileKeys, params);
}
public static void postAsyn(String url, ResultCallback callback, File file, String fileKey) throws IOException
{
getInstance()._postAsyn(url, callback, file, fileKey);
}
public static void postAsyn(String url, ResultCallback callback, File file, String fileKey, Param… params) throws IOException
{
getInstance()._postAsyn(url, callback, file, fileKey, params);
}
public static void displayImage(final ImageView view, String url, int errorResId) throws IOException
{
getInstance()._displayImage(view, url, errorResId);
}
public static void displayImage(final ImageView view, String url)
{
getInstance()._displayImage(view, url, -1);
}
public static void downloadAsyn(String url, String destDir, ResultCallback callback)
{
getInstance()._downloadAsyn(url, destDir, callback);
}
//****************************
private Request buildMultipartFormRequest(String url, File[] files,
String[] fileKeys, Param[] params)
{
params = validateParam(params);
MultipartBuilder builder = new MultipartBuilder()
.type(MultipartBuilder.FORM);
for (Param param : params)
{
builder.addPart(Headers.of(“Content-Disposition”, “form-data; name=”" + param.key + “”"),
RequestBody.create(null, param.value));
}
if (files != null)
{
RequestBody fileBody = null;
for (int i = 0; i < files.length; i++)
{
File file = files[i];
String fileName = file.getName();
fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
//TODO 根据文件名设置contentType
builder.addPart(Headers.of(“Content-Disposition”,
“form-data; name=”" + fileKeys[i] + “”; filename=“” + fileName + “”"),
fileBody);
}
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
private String guessMimeType(String path)
{
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = fileNameMap.getContentTypeFor(path);
if (contentTypeFor == null)
{
contentTypeFor = “application/octet-stream”;
}
return contentTypeFor;
}
private Param[] validateParam(Param[] params)
{
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
尾声
你不踏出去一步,永远不知道自己潜力有多大,千万别被这个社会套在我们身上的枷锁给捆住了,30岁我不怕,35岁我一样不怕,去做自己想做的事,为自己拼一把吧!不试试怎么知道你不行呢?
改变人生,没有什么捷径可言,这条路需要自己亲自去走一走,只有深入思考,不断反思总结,保持学习的热情,一步一步构建自己完整的知识体系,才是最终的制胜之道,也是程序员应该承担的使命。
附上:我们之前因为秋招收集的二十套一二线互联网公司Android面试真题(含BAT、小米、华为、美团、滴滴)和我自己整理Android复习笔记(包含Android基础知识点、Android扩展知识点、Android源码解析、设计模式汇总、Gradle知识点、常见算法题汇总。)
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
tTypeFor(path);
if (contentTypeFor == null)
{
contentTypeFor = “application/octet-stream”;
}
return contentTypeFor;
}
private Param[] validateParam(Param[] params)
{
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-Xsfy1TyT-1712341124803)]
[外链图片转存中…(img-9xVqWz3c-1712341124804)]
[外链图片转存中…(img-oocjDnWs-1712341124804)]
[外链图片转存中…(img-XdGvp4cV-1712341124804)]
[外链图片转存中…(img-7Gt5P6Pt-1712341124805)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
尾声
你不踏出去一步,永远不知道自己潜力有多大,千万别被这个社会套在我们身上的枷锁给捆住了,30岁我不怕,35岁我一样不怕,去做自己想做的事,为自己拼一把吧!不试试怎么知道你不行呢?
改变人生,没有什么捷径可言,这条路需要自己亲自去走一走,只有深入思考,不断反思总结,保持学习的热情,一步一步构建自己完整的知识体系,才是最终的制胜之道,也是程序员应该承担的使命。
附上:我们之前因为秋招收集的二十套一二线互联网公司Android面试真题(含BAT、小米、华为、美团、滴滴)和我自己整理Android复习笔记(包含Android基础知识点、Android扩展知识点、Android源码解析、设计模式汇总、Gradle知识点、常见算法题汇总。)
[外链图片转存中…(img-LrQkh7dl-1712341124805)]
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!