import java.io.UnsupportedEncodingException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rl.mobile.R;
import com.rl.mobile.entity.HttpDetails;
import com.rl.mobile.view.customize.HttpCallBackListener;
import android.app.ActivityManager;
import android.content.Context;
import android.widget.ImageView;
//网络请求
public class VolleyUtils
{
private static VolleyUtils instance;
//请求队列
private static RequestQueue mRequestQueue;
//创建ImageLoader
private static ImageLoader mImageLoader;
//默认分配最大空间的几分之几
private final static int RATE=8;
public VolleyUtils(Context context){
//初始化请求队列(默认创建5个线程)
mRequestQueue=Volley.newRequestQueue(context);
//获取ActivityManager管理者
ActivityManager manager=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int maxSize=manager.getMemoryClass()/RATE;
//初始化ImageLoader对象
mImageLoader=new ImageLoader(mRequestQueue, new BitmapLruCache(1024*1024*maxSize));
}
/**
* Volley的初始化操作,使用volley前必须调用此方法
*/
public static void init(Context context){
if(instance==null){
instance=new VolleyUtils(context);
}
}
/**
* 获取消息队列
*/
public static RequestQueue getRequestQueue(){
throwIfNotInit();
return mRequestQueue;
}
/**
* 获取ImageLoader
*/
public static ImageLoader getImageLoader(){
throwIfNotInit();
return mImageLoader;
}
/**
* 加入请求队列
*/
public static void addRequest(Request<?> request){
getRequestQueue().add(request);
}
/**
* 加载网络图片
*/
public static void getImage(String requestUrl, ImageView imageView)
{
if(!MStringUtils.isNullOrEmpty(requestUrl))
{
getImage(requestUrl, imageView, 0, 0);
}
}
/**
* 加载网络图片
*/
public static void getImage(String requestUrl, ImageView imageView, int maxWidth, int maxHeight,boolean isHeight)
{
if(!MStringUtils.isNullOrEmpty(requestUrl))
{
imageView.setTag(requestUrl);
try {
getImageLoader().get(requestUrl,ImageListenerFactory.getImageListener(imageView,0, 0), maxWidth, maxHeight);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 加载网络图片
*/
public static void getImageNo(String requestUrl, ImageView imageView, int maxWidth, int maxHeight,boolean isHeight)
{
if(!MStringUtils.isNullOrEmpty(requestUrl))
{
imageView.setTag(requestUrl);
try {
getImageLoader().get(requestUrl,ImageListenerFactory.getImageListenerNo(imageView,0, 0), maxWidth, maxHeight);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 加载网络图片
*
*/
public static void getImage(String requestUrl, ImageView imageView,
int defaultImageResId, int errorImageResId) {
getImage(requestUrl, imageView, defaultImageResId, errorImageResId, 0,
0);
}
/**
* 加载网络图片
*
*/
public static void getImage(String requestUrl, ImageView imageView,
int defaultImageResId, int errorImageResId, int maxWidth,
int maxHeight) {
imageView.setTag(requestUrl);
try {
getImageLoader().get(
requestUrl,
ImageListenerFactory.getImageListener(imageView,
defaultImageResId, errorImageResId), maxWidth,
maxHeight);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 检查是否完成初始化
*/
private static void throwIfNotInit() {
if (instance == null) {
throw new IllegalStateException("VolleyUtils尚未初始化,在使用前应该执行init()");
}
}
/**
* http 请求
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postStringRequestArray(Context context,String endIp,final Map<String, String> map,
final HttpCallBackListener listener,boolean dialogCancelable)
{
if(context!=null)
{
NewDialogUtils.setNewDialog(context);
}
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
NewDialogUtils.dismissNewDialog();
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
listener.onSuccess(GsonUtil.getJsonArray(s, "data"));
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(s, "errMsg"))?GsonUtil.getJsonStr(s, "errMsg"): Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
listener.onSuccess("");
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
NewDialogUtils.dismissNewDialog();
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
}
});
addRequest(request);
}
/**
* http 请求无dialog
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postStringRequestArray(String endIp,final Map<String, String> map,
final HttpCallBackListener listener)
{
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
listener.onSuccess(GsonUtil.getJsonArray(s, "data"));
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(s, "errMsg"))?GsonUtil.getJsonStr(s, "errMsg"):Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
listener.onSuccess("");
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
listener.onError(error);
}
});
addRequest(request);
}
/**
* http 请求 无dialog,无toast
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postStringRequestArrayNoToast(String endIp,final Map<String, String> map,
final HttpCallBackListener listener)
{
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
listener.onSuccess(GsonUtil.getJsonArray(s, "data"));
}
else
{
listener.onSuccess("");
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
listener.onError(error);
}
});
addRequest(request);
}
/**
* http 请求
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postStringRequest(Context context,String endIp,final Map<String, String> map,
final HttpCallBackListener listener,boolean dialogCancelable)
{
if(context!=null)
{
NewDialogUtils.setNewDialog(context);
}
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
NewDialogUtils.dismissNewDialog();
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
listener.onSuccess(GsonUtil.getJsonData(s, "data"));
}
else
{
if(GsonUtil.getJsonStr(s, "errMsg").equals("数据中存在收藏的数据,请去除后重新收藏~"))
{
listener.onSuccess(GsonUtil.getJsonData(s, "data"));
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(s, "errMsg"))?GsonUtil.getJsonStr(s, "errMsg"): Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
}
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
NewDialogUtils.dismissNewDialog();
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
listener.onError(error);
}
});
addRequest(request);
}
/**
* http 请求(微信朋友圈分享前调用)
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postShareRequest(final Context context, String endIp,final Map<String, String> map,
final HttpCallBackListener listener,boolean dialogCancelable)
{
if(context!=null)
{
NewDialogUtils.setNewDialog(context);
}
String url = Constant.HTTP_SHARE+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
NewDialogUtils.dismissNewDialog();
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
HttpDetails details = GsonUtil.getJSONEntitiy(s, HttpDetails.class);
listener.onSuccess(details.getData());
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(s, "errMsg"))?GsonUtil.getJsonStr(s, "errMsg"):Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
NewDialogUtils.dismissNewDialog();
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
listener.onError(error);
}
});
addRequest(request);
}
/**
* http 请求 无Dialog
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postStringRequest(final Context context, String endIp,final Map<String, String> map,
final HttpCallBackListener listener)
{
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
listener.onSuccess(GsonUtil.getJsonData(s, "data"));
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(s, "errMsg"))?GsonUtil.getJsonStr(s, "errMsg"):Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
listener.onError(error);
}
});
addRequest(request);
}
/**
* http 请求 首页行事历待办数 返回total 不是data
*/
public static void postStringNodata(final Context context, String endIp,final Map<String, String> map,
final HttpCallBackListener listener)
{
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
listener.onSuccess(GsonUtil.getJsonInt(s, "total"));
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(s, "errMsg"))?GsonUtil.getJsonStr(s, "errMsg"):Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
String error=Constant.HTTP_ERROR;
listener.onError(error);
}
});
addRequest(request);
}
/**
* http 请求 无dialog
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postStringRequest(final Context context, String endIp,final Map<String, String> map
)
{
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(s, "errMsg"))?GsonUtil.getJsonStr(s, "errMsg"):Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
}
});
addRequest(request);
}
/**
* http 无dialog,无toast
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postStringRequestNoToast(final Context context, String endIp,final Map<String, String> map,
final HttpCallBackListener listener)
{
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(s)&&GsonUtil.getJsonStr(s, "errCode").equals(ResUtil.getString(R.string.str_success)))
{
listener.onSuccess(GsonUtil.getJsonData(s, "data"));
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
}
});
addRequest(request);
}
/**
* http 只请求,不做任何操作
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
*/
public static void postStringRequestNoToast(String endIp,final Map<String, String> map)
{
String url = Constant.HTTP_IP+endIp;
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,map, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
}
});
addRequest(request);
}
/**
* 获取ip地址
* @return
*/
public static String getHostIP() {
String hostIp = "";
try {
Enumeration<?> nis = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {
ia = ias.nextElement();
if (ia instanceof Inet6Address) {
continue;// skip ipv6
}
String ip = ia.getHostAddress();
if (!"127.0.0.1".equals(ip)) {
hostIp = ia.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return hostIp;
}
/**
* http 请求
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
* @throws Exception
*/
public static void postStringRequestRl(Context context,String endIp,final Map<String, Object> map,
final HttpCallBackListener listener,boolean dialogCancelable)
{
if(context!=null)
{
NewDialogUtils.setNewDialog(context);
}
String url = Constant.HTTP_IP_L+endIp;
map.put("sysId","0");
map.put("requestNo","0");
String bizContent = GsonUtil.toJSONString(map);
//必须要重新设置url编码后的值
String encrypt = null;
try {
encrypt = URLEncoder.encode(bizContent, "utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("requestTime", MDateUtils.getNowLongTime());
paramMap.put("content", encrypt);
paramMap.put("sign", "");
paramMap.put("charset", "UTF-8");
paramMap.put("signType", "MD5");
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,paramMap, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
NewDialogUtils.dismissNewDialog();
Map<String, String> paramMap= new Gson().fromJson(s, new TypeToken<Map<String, String>>() {}.getType());
String bizContent=null;
try {
bizContent=URLDecoder.decode(paramMap.get("content"), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(bizContent)&&GsonUtil.getJsonStr(bizContent, "message").equals(ResUtil.getString(R.string.str_rlsuccess)))
{
listener.onSuccess(GsonUtil.getJsonData(bizContent, "data"));
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(bizContent, "message"))?GsonUtil.getJsonStr(bizContent, "message"):Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
NewDialogUtils.dismissNewDialog();
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
listener.onError(error);
}
});
addRequest(request);
}
/**
* http 请求
* @param context
* @param endIp
* @param map
* @param listener
* @param errorListener
* @throws Exception
*/
public static void postStringRequestArrayRl(Context context,String endIp,final Map<String, Object> map,
final HttpCallBackListener listener,boolean dialogCancelable)
{
if(context!=null)
{
NewDialogUtils.setNewDialog(context);
}
String url = Constant.HTTP_IP_L+endIp;
map.put("sysId","0");
map.put("requestNo","0");
String bizContent = GsonUtil.toJSONString(map);
//必须要重新设置url编码后的值
String encrypt = null;
try {
encrypt = URLEncoder.encode(bizContent, "utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("requestTime", MDateUtils.getNowLongTime());
paramMap.put("content", encrypt);
paramMap.put("sign", "");
paramMap.put("charset", "UTF-8");
paramMap.put("signType", "MD5");
HeaderStringRequest request = new HeaderStringRequest(Request.Method.POST, url,paramMap, new Response.Listener<String>() {
@Override
public void onResponse(String s)
{
NewDialogUtils.dismissNewDialog();
Map<String, String> paramMap= new Gson().fromJson(s, new TypeToken<Map<String, String>>() {}.getType());
String bizContent=null;
try {
bizContent=URLDecoder.decode(paramMap.get("content"), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//返回字段不为空,errMsg不为空
if(!MStringUtils.isNullOrEmpty(bizContent)&&GsonUtil.getJsonStr(bizContent, "message").equals(ResUtil.getString(R.string.str_rlsuccess)))
{
listener.onSuccess(bizContent);
}
else
{
String errMsg=!MStringUtils.isNullOrEmpty(GsonUtil.getJsonStr(bizContent, "message"))?GsonUtil.getJsonStr(bizContent, "message"):Constant.HTTP_RESPONSEERROR;
ToastUtils.showMessage(errMsg);
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
NewDialogUtils.dismissNewDialog();
String error=Constant.HTTP_ERROR;
ToastUtils.showMessage(error);
listener.onError(error);
}
});
addRequest(request);
}
}