//OkHttp3练习util
// compile ‘com.squareup.okhttp3:okhttp:3.4.1’
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import org.apache.commons.collections.map.HashedMap;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by ios13 on 17/9/21.
*/
public class OKHttpUtil {
private static OkHttpClient okHttpClient;
public static final MediaType MIXED = MediaType.parse(“multipart/mixed”);
public static final MediaType ALTERNATIVE = MediaType.parse(“multipart/alternative”);
public static final MediaType DIGEST = MediaType.parse(“multipart/digest”);
public static final MediaType PARALLEL = MediaType.parse(“multipart/parallel”);
public static final MediaType FORM = MediaType.parse(“multipart/form-data”);
/*通过MediaType.parse("text/plain; charset=utf-8")为上传文件设置一定类型(MIME)
在这里我们上传的纯文本文件所以选择"text/plain类型,而编码格式为utf-8。"
下面为大家列出常见的文件类型,方便使用。
参数 说明
text/html HTML格式
text/plain 纯文本格式
text/xml XML格式
image/gif gif图片格式
image/jpeg jpg图片格式
image/png png图片格式
application/xhtml+xml XHTML格式
application/xml XML数据格式
application/atom+xml Atom XML聚合格式
application/json JSON数据格式
application/pdf pdf格式
application/msword Word文档格式
application/octet-stream 二进制流数据*/
/**
* get请求
*
* @param url
*/
public static String getAsynHttp(String url) {
final Map<String, Object> map = new HashedMap();
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
map.put("Code", 201);
map.put("data", null);
map.put("msg", "error");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
/* if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}*/
String json = response.body().string();
map.put("Code", 200);
map.put("data", json);
map.put("msg", "success");
}
});
net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(map);
while (jsonobject.size()==0){
jsonobject = net.sf.json.JSONObject.fromObject(map);
}
//String y=JSONArray.fromObject(map).toString();
return jsonobject.toString();
}
/**
* 传递josn数据通过post
*
* @param url url链接
* @param json json字符串
* @return
* @throws Exception
*/
public static String postJson(String url, String json) throws Exception {
final Map<String, Object> map = new HashedMap();
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
MediaType JSONs = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSONs, json);
Request request = new Request.Builder().url(url).post(body).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
map.put("Code", 201);
map.put("msg", "error");
map.put("data", null);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
map.put("Code", 200);
map.put("data", json);
map.put("msg", "success");
}
});
net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(map);
while (jsonobject.size()==0){
jsonobject = net.sf.json.JSONObject.fromObject(map);
}
//String y=JSONArray.fromObject(map).toString();
return jsonobject.toString();
}
/**
* 异步请求
*
* @param url 地址
* @param map 参数
* @param method 请求方式
* @return
*/
public static String asynHttpBymap(String url, Map<String, Object> map, String method) {
final Map<String, Object> maps = new HashedMap();
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
FormBody.Builder builder = new FormBody.Builder();
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
builder.add(it.next().toString(), map.get(it.next().toString()).toString());
}
RequestBody body = builder.build();
Request request = new Request.Builder().url(url).method(method, body).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
maps.put("Code", 201);
maps.put("msg", "error");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
maps.put("Code", 200);
maps.put("data", json);
maps.put("msg", "success");
}
});
net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(maps);
while (jsonobject.size()==0){
jsonobject = net.sf.json.JSONObject.fromObject(maps);
}
return jsonobject.toString();
}
/**
* 通过javabean 异步请求
*
* @param url 地址
* @param bean javabean
* @param ishavenull 是否传递空值
* @param method 请求方式
* @throws Exception
*/
public static String asynHttpByBean(String url, Object bean, Boolean ishavenull, String method) throws Exception {
if (ishavenull) {
Map<String, Object> map = BeanToMap(bean);
return asynHttpBymap(url, map, method);
} else {
Map<String, Object> map = BeanToMapNotNull(bean);
return asynHttpBymap(url, map, method);
}
}
/**
* post获取数据
*
* @param url 地址
* @param map 参数集合
* @return
*/
public static String postAsynHttpByMap(String url, Map<String, Object> map) {
final Map<String, Object> maps = new HashedMap();
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
FormBody.Builder builder = new FormBody.Builder();
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
builder.add(it.next().toString(), map.get(it.next().toString()).toString());
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder().url(url).post(requestBody).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
maps.put("Code", 201);
maps.put("msg", "error");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
maps.put("Code", 200);
maps.put("data", json);
maps.put("msg", "success");
}
});
net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(maps);
while (jsonobject.size()==0){
jsonobject = net.sf.json.JSONObject.fromObject(maps);
}
//String y=JSONArray.fromObject(map).toString();
return jsonobject.toString();
}
/**
* 通过bean 进行post请求
*
* @param url 地址
* @param bean javabean
* @param ishavenull 是否传递空值参
* @return
* @throws Exception
*/
public static String postAsynHttpByBean(String url, Object bean, Boolean ishavenull) throws Exception {
if (ishavenull) {
Map<String, Object> map = BeanToMap(bean);
return postAsynHttpByMap(url, map);
} else {
Map<String, Object> map = BeanToMapNotNull(bean);
return postAsynHttpByMap(url, map);
}
}
/**
* bean转map 空值不忽略static
*
* @param obj bean
* @return
* @throws Exception
*/
private static Map<String, Object> BeanToMap(Object obj) throws Exception {
Field[] fields = obj.getClass().getDeclaredFields();
Map<String, Object> map = new HashMap();
for (Field field : fields) {
//String type=fields[i].getType().toString();
String name = field.getName();
if (!name.equals("serialVersionUID") && !name.equals("$change")) {
// 获取属性的名字
// 将属性的首字符大写,方便构造get,set方法
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 获取属性的类型
String type = field.getGenericType().toString();
Method m = obj.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Object value = m.invoke(obj);
map.put(field.getName(), value);
}
}
return map;
}
/**
* bean转map 空值忽略static
*
* @param obj bean
* @return
* @throws Exception
*/
private static Map<String, Object> BeanToMapNotNull(Object obj) throws Exception {
Field[] fields = obj.getClass().getDeclaredFields();
Map<String, Object> map = new HashMap();
for (Field field : fields) {
//String type=fields[i].getType().toString();
String name = field.getName();
if (!name.equals("serialVersionUID") && !name.equals("$change")) {
// 获取属性的名字
// 将属性的首字符大写,方便构造get,set方法
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 获取属性的类型
String type = field.getGenericType().toString();
Method m = obj.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Object value = m.invoke(obj);
if (value != null) {
map.put(field.getName(), value);
}
}
}
return map;
}
/**
* 上传文件
*
* @param url
* @param file
*/
public static String Upload(String url, File file) {
final Map<String, Object> maps = new HashedMap();
// step 1: 创建 OkHttpClient 对象
okHttpClient = new OkHttpClient();
//step 2:创建 RequestBody 以及所需的参数
//2.1 获取文件
// File file = new File(Environment.getExternalStorageDirectory() + "test.txt");
//2.2 创建 MediaType 设置上传文件类型
MediaType MEDIATYPE = MediaType.parse("text/plain; charset=utf-8");
//2.3 获取请求体
RequestBody requestBody = RequestBody.create(MEDIATYPE, file);
//step 3:创建请求
Request request = new Request.Builder().url(url)
.post(requestBody)
.build();
//step 4 建立联系
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// TODO: 请求失败
maps.put("Code", 201);
maps.put("msg", "error");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// TODO:请求成功
String json = response.body().string();
maps.put("Code", 200);
maps.put("data", json);
maps.put("msg", "success");
}
});
return JSONArray.fromObject(maps).toString();
}
/**
* @param url 下载连接
* @param saveDir 储存下载文件的SDCard目录
* @param listener 下载监听
*/
public static void download(final String url, final String saveDir, final OnDownloadListener listener) {
/**
* 动态获取权限,Android 6.0 新特性,一些保护权限,除了要在AndroidManifest中声明权限,还要使用如下代码动态获取
*/
okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下载失败
listener.onDownloadFailed();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
// 储存下载文件的目录
String savePath = isExistDir(saveDir);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
File file = new File(savePath, getNameFromUrl(url));
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
// 下载中
listener.onDownloading(progress);
}
fos.flush();
// 下载完成
listener.onDownloadSuccess();
} catch (Exception e) {
listener.onDownloadFailed();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
});
}
/**
* @param saveDir
* @return
* @throws IOException 判断下载目录是否存在
*/
private static String isExistDir(String saveDir) throws IOException {
// 下载位置
File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
if (!downloadFile.mkdirs()) {
downloadFile.createNewFile();
}
String savePath = downloadFile.getAbsolutePath();
return savePath;
}
/**
* 获取文件名
*
* @param url
* @return 从下载连接中解析出文件名
*/
private static String getNameFromUrl(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}
/**
* 下载进度
*/
public interface OnDownloadListener {
/**
* 下载成功
*/
void onDownloadSuccess();
/**
* @param progress 下载进度
*/
void onDownloading(int progress);
/**
* 下载失败
*/
void onDownloadFailed();
}
}
引用块内容