最简单的okhttp封装,CallBack方法执行在UI线程。支持get请求,post请求,支持文件上传和下载。
代码很简单,只有三个Java文件,建议下载后将Java文件拷贝到工程中使用。
String url = "https://www.baidu.com/";
OkhttpUtil.okHttpGet(url, new CallBackUtil.CallBackString() {
@Override
public void onFailure(Call call, Exception e) {}
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this,"Success",Toast.LENGTH_SHORT).show();
Log.d("kwwl",response);
}
});
String url = "https://www.baidu.com/";
HashMap<String, String> paramsMap = new HashMap<>();
paramsMap.put("title","title");
OkhttpUtil.okHttpPost(url, paramsMap, new CallBackUtil.CallBackString() {
@Override
public void onFailure(Call call, Exception e) {
}
@Override
public void onResponse(String response) {
}
});
String url = "https://www.baidu.com/";
HashMap<String, String> paramsMap = new HashMap<>();
paramsMap.put("title","title");
OkhttpUtil.okHttpPut(url, paramsMap, new CallBackUtil.CallBackString() {
@Override
public void onFailure(Call call, Exception e) {
}
@Override
public void onResponse(String response) {
}
});
String url = "https://www.baidu.com/";
HashMap<String, String> paramsMap = new HashMap<>();
paramsMap.put("title","title");
OkhttpUtil.okHttpDelete(url, paramsMap, new CallBackUtil.CallBackString() {
@Override
public void onFailure(Call call, Exception e) {
}
@Override
public void onResponse(String response) {
}
});
File file = new File(Environment.getExternalStorageDirectory()+"/kwwl/abc.jpg");
HashMap<String, String> paramsMap = new HashMap<>();
paramsMap.put("title","title");
OkhttpUtil.okHttpUploadFile(url, file, "image", OkhttpUtil.FILE_TYPE_IMAGE, paramsMap, new CallBackUtil.CallBackString() {
@Override
public void onFailure(Call call, Exception e) {
}
@Override
public void onProgress(float progress, long total) {
}
@Override
public void onResponse(String response) {
}
});
OkhttpUtil.okHttpDownloadFile("url", new CallBackUtil.CallBackFile("fileDir","fileName") {
@Override
public void onFailure(Call call, Exception e) {
}
@Override
public void onProgress(float progress, long total) {
}
@Override
public void onResponse(File response) {
}
});