首先准备工作,项目以As为演示,所以直接添加的依赖库,如果使用的是Eclipse,自己可以在网上找对应的jar包。
compile 'com.mcxiaoke.volley:library:1.0.19'
compile "com.squareup.okhttp3:okhttp:3.7.0"
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
还有网络权限不要忘记
测试接口准备:
public class Const {
//参数 num = 手机号
public static final String GETURL = "http://route.showapi.com/6-1?num=";
public static final String POSTURL = "http://route.showapi.com/6-1";
}
使用Volley时需要一个全局的请求队列,这里我们需要做一些准备工作:
1、重写一个MyApplicatin,在Application中声明消息队列
/**
* Created by LJZ on 2018/10/8.
*/
public class MyApplication extends Application {
public static RequestQueue queues;//全局消息队列
@Override
public void onCreate() {
super.onCreate();
queues = Volley.newRequestQueue(getApplicationContext()); //实例化全局队列
}
public static RequestQueue getHttpQueues(){
return queues;
}
}
不要忘了在manifest文件中指定MyApplication
private void VolleyGet() {
StringRequest request = new StringRequest(Request.Method.GET, Const.GETURL+telNum, new Response.Listener() {
@Override
public void onResponse(String response) {
Log.e("info","Volley Get请求成功结果"+response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
request.setTag("volleyGet");
MyApplication.getHttpQueues().add(request);
}
最后不要忘记在onStop中取消请求
@Override
protected void onStop() {
super.onStop();
MyApplication.getHttpQueues().cancelAll("volleyGet");
}
private void VolleyPost() {
StringRequest request = new StringRequest(Request.Method.POST, Const.POSTURL, new Response.Listener() {
@Override
public void onResponse(String response) {
Log.e("info","Volley Post请求成功结果"+response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map getParams() throws AuthFailureError {
Map volleyPostMap = new HashMap<>();
volleyPostMap.put("num",telNum);
return super.getParams();
}
};
request.setTag("volleyPost");
MyApplication.getHttpQueues().add(request);
}
最后不要忘记在onStop中取消请求
@Override
protected void onStop() {
super.onStop();
MyApplication.getHttpQueues().cancelAll("volleyPost");
}
VolleyInterface.java 请求结果回调
public abstract class VolleyInterface {
public Context mContext;
public static Response.Listener mListener;
public static Response.ErrorListener mErrorListener;
public VolleyInterface(Context context, Response.Listener listener, Response.ErrorListener errorListener){
this.mContext = context;
this.mListener = listener;
this.mErrorListener = errorListener;
}
public abstract void onMySuccess(String result);
public abstract void onMyError(VolleyError error);
//请求成功的回调方法
public Response.Listener loadingListener(){
mListener = new Response.Listener() {
@Override
public void onResponse(String response) {
onMySuccess(response);
}
};
return mListener;
}
//请求失败的回调方法
public Response.ErrorListener errorListener(){
mErrorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onMyError(error);
}
};
return mErrorListener;
}
}
VollyRequest.java 请求方法类
public class VolleyRequest {
private static StringRequest stringRequest;
private static Context context;
public static void RequestGet(Context mContext,String url,String tag,VolleyInterface vif){
MyApplication.getHttpQueues().cancelAll(tag);
stringRequest = new StringRequest(Request.Method.GET,url, vif.loadingListener(),vif.errorListener());
stringRequest.setTag(tag);
MyApplication.getHttpQueues().add(stringRequest);
MyApplication.getHttpQueues().start();
}
public static void RequestPost(Context mContext, String url, String tag, final Map params
, VolleyInterface vif){
MyApplication.getHttpQueues().cancelAll(tag);
stringRequest = new StringRequest(Request.Method.POST,url,vif.loadingListener(),vif.errorListener()){
@Override
protected Map getParams() throws AuthFailureError {
return params;
}
};
stringRequest.setTag(tag);
MyApplication.getHttpQueues().add(stringRequest);
MyApplication.getHttpQueues().start();
}
}
使用
VolleyRequest.RequestGet(MainActivity.this, Const.GETURL + telNum, "volleyGet2", new VolleyInterface(this,
VolleyInterface.mListener,VolleyInterface.mErrorListener) {
@Override
public void onMySuccess(String result) {
Log.e("info","封装请求Get结果"+result);
}
@Override
public void onMyError(VolleyError error) {
}
});
Map postMap = new HashMap<>();
postMap.put("num",telNum);
VolleyRequest.RequestPost(MainActivity.this, Const.POSTURL, "volleyPost2", postMap, new VolleyInterface(MainActivity.this,
VolleyInterface.mListener,VolleyInterface.mErrorListener) {
@Override
public void onMySuccess(String result) {
Log.e("info","封装请求Post结果"+result);
}
@Override
public void onMyError(VolleyError error) {
}
});
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS) //设置读取数据的时间
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(Const.GETURL+telNum)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
Log.e("info","OkHttp get请求成功结果"+response.body().string());
}
});
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(5,TimeUnit.SECONDS)
.build();
RequestBody body = new FormBody.Builder()
.add("num",telNum)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(Const.POSTURL)
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
Log.e("info","OkHttp Post请求成功结果"+response.body().string());
}
});
OkHttpManager.java这是网上一个大神封装好的类,可以直接用
/**
* Created by 若兰 on 2016/1/23.
* csdn:http://blog.csdn.net/wuyinlei
*/
public class OkHttpManager {
private final String TAG = OkHttpManager.class.getSimpleName();
private final String NETWORK_FAILURE = "联网失败,请检查网络设置!";
/**
* 静态实例
*/
private static OkHttpManager sOkHttpManager;
/**
* okhttpclient实例
*/
private OkHttpClient mClient;
/**
* 因为我们请求数据一般都是子线程中请求,在这里我们使用了handler
*/
private Handler mHandler;
/**
* 构造方法
*/
private OkHttpManager() {
mClient = new OkHttpClient();
/**
* 在这里直接设置连接超时.读取超时,写入超时
*/
mClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
mClient.newBuilder().readTimeout(10, TimeUnit.SECONDS);
mClient.newBuilder().writeTimeout(10, TimeUnit.SECONDS);
/**
* 如果是用的3.0之前的版本 使用以下直接设置连接超时.读取超时,写入超时
*/
// client.setConnectTimeout(10, TimeUnit.SECONDS);
// client.setWriteTimeout(10, TimeUnit.SECONDS);
// client.setReadTimeout(30, TimeUnit.SECONDS);
/**
* 初始化handler
*/
mHandler = new Handler(Looper.getMainLooper());
}
/**
* 单例模式 获取OkHttpManager实例
*
* @return
*/
public static OkHttpManager getInstance() {
if (sOkHttpManager == null) {
sOkHttpManager = new OkHttpManager();
}
return sOkHttpManager;
}
/*
* 判断是否已经连接网络
*
* @param context
*
* @return
*/
public boolean isNetWorkAvailable(Context context) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
return true;
}
return false;
}
/**
* 打开网络设置界面
*
* @param activity
*/
public void openSettings(Activity activity) {
if (android.os.Build.VERSION.SDK_INT > 13) {// 3.2以上打开设置界面,也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面
activity.startActivity(new Intent(
android.provider.Settings.ACTION_SETTINGS));
} else {
activity.startActivity(new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
}
// -------------------------同步的方式请求数据--------------------------
/**
* 对外提供的get方法,同步的方式
*
* @param url
* 传入的地址
* @return
*/
public static Response getSync(String url) {
// 通过获取到的实例来调用内部方法
return getInstance().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 getInstance().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) {
callBack.requestFailure(request, e, NETWORK_FAILURE);
}
}
});
}
/**
* 分发成功的时候调用
*
* @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 {
String requestSuccess(String result);
void requestFailure(Request request, IOException e, String failStr);
}
// -------------------------提交表单--------------------------
public static void postAsync(String url, Map params,
DataCallBack callBack) {
getInstance().inner_postAsync(url, params, callBack);
}
private void inner_postAsync(String url, Map 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 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);
}
});
}
// -------------------------文件下载--------------------------
public static void downloadAsync(String url, String desDir,
DataCallBack callBack) {
getInstance().inner_downloadAsync(url, desDir, callBack);
}
/**
* 下载文件的内部逻辑处理类
*
* @param url
* 下载地址
* @param desDir
* 目标地址
* @param callBack
*/
private void inner_downloadAsync(final String url, final String desDir,
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 {
/**
* 在这里进行文件的下载处理
*/
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
// 文件名和目标地址
File file = new File(desDir, getFileName(url));
// 把请求回来的response对象装换为字节流
inputStream = response.body().byteStream();
fileOutputStream = new FileOutputStream(file);
int len = 0;
byte[] bytes = new byte[2048];
// 循环读取数据
while ((len = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
// 关闭文件输出流
fileOutputStream.flush();
// 调用分发数据成功的方法
deliverDataSuccess(file.getAbsolutePath(), callBack);
} catch (IOException e) {
// 如果失败,调用此方法
deliverDataFailure(request, e, callBack);
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}
});
}
/**
* 根据文件url获取文件的路径名字
*
* @param url
* @return
*/
private String getFileName(String url) {
int separatorIndex = url.lastIndexOf("/");
String path = (separatorIndex < 0) ? url : url.substring(
separatorIndex + 1, url.length());
return path;
}
/**
* 上传图片
*
* @param url
* @return
*/
public static void postAsyn(String url, DataCallBack callback, File file,
String fileKey, Param... params) throws IOException {
getInstance()._postAsyn(url, callback, file, fileKey, params);
}
/**
* 异步基于post的文件上传,单文件且携带其他form参数上传
*
* @param url
* @param callback
* @param file
* @param fileKey
* @param params
* @throws IOException
*/
private void _postAsyn(String url, DataCallBack callback, File file,
String fileKey, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, new File[] { file },
new String[] { fileKey }, params);
deliveryResult(callback, request);
}
private Request buildMultipartFormRequest(String url, File[] files,
String[] fileKeys, Param[] params) {
params = validateParam(params);
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.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);
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 void deliveryResult(final DataCallBack callback,
final Request request) {
mClient.newCall(request).enqueue(new Callback() {
// @Override
// public void onFailure(final Request request, final IOException e)
// {
// sendFailedStringCallback(request, e, callback);
// }
//
// @Override
// public void onResponse(final Response response)
// {
// try
// {
// final String string = response.body().string();
// if (callback.mType == String.class)
// {
// sendSuccessResultCallback(string, callback);
// } else
// {
// Object o = mGson.fromJson(string, callback.mType);
// sendSuccessResultCallback(o, callback);
// }
//
//
// } catch (IOException e)
// {
// sendFailedStringCallback(response.request(), e, callback);
// } catch (com.google.gson.JsonParseException e)//Json解析的错误
// {
// sendFailedStringCallback(response.request(), e, 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 void sendFailedStringCallback(final Request request, final
// Exception e, final DataCallBack callback)
// {
// mHandler.post(new Runnable()
// {
// @Override
// public void run()
// {
// if (callback != null)
// callback.requestFailure(request, e);
// // callback.onError(request, e);
// }
// });
// }
//
// private void sendSuccessResultCallback(final Object object, final
// DataCallBack callback)
// {
// mHandler.post(new Runnable()
// {
// @Override
// public void run()
// {
// if (callback != null)
// {
// callback.requestSuccess(object);
// }
// }
// });
// }
private Param[] validateParam(Param[] params) {
if (params == null)
return new Param[0];
else
return params;
}
public static class Param {
public Param() {
}
public Param(String key, String value) {
this.key = key;
this.value = value;
}
String key;
String value;
}
}
OkHttpManager.getAsync(Const.GETURL + telNum, new OkHttpManager.DataCallBack() {
@Override
public String requestSuccess(String result) {
Log.e("info","OkHttp封装请求Get结果"+result);
return result;
}
@Override
public void requestFailure(okhttp3.Request request, IOException e, String failStr) {
}
});
Map postMap = new HashMap<>();
postMap.put("num",telNum);
OkHttpManager.postAsync(Const.POSTURL, postMap, new OkHttpManager.DataCallBack() {
@Override
public String requestSuccess(String result) {
Log.e("info","OkHttp封装请求Post结果"+result);
return result;
}
@Override
public void requestFailure(okhttp3.Request request, IOException e, String failStr) {
}
});
使用步骤
1、创建Model类
/**
* Created by LJZ on 2018/10/10.
*/
public class MoblieInfoModel {
/**
* showapi_res_error : showapi_appid字段必传
* showapi_res_code : -1002
* showapi_res_body : {}
*/
private String showapi_res_error;
private int showapi_res_code;
private ShowapiResBodyBean showapi_res_body;
public String getShowapi_res_error() {
return showapi_res_error;
}
public void setShowapi_res_error(String showapi_res_error) {
this.showapi_res_error = showapi_res_error;
}
public int getShowapi_res_code() {
return showapi_res_code;
}
public void setShowapi_res_code(int showapi_res_code) {
this.showapi_res_code = showapi_res_code;
}
public ShowapiResBodyBean getShowapi_res_body() {
return showapi_res_body;
}
public void setShowapi_res_body(ShowapiResBodyBean showapi_res_body) {
this.showapi_res_body = showapi_res_body;
}
public static class ShowapiResBodyBean {
}
}
2、创建接口设置请求类型与参数
public interface UserMgrGetService {
@GET("6-1")
Call getMessage(@Query("num") String num);
}
3、创建Retrofit对象,设置数据解析器
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Const.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
4、生成接口对象
UserMgrPostService service = retrofit.create(UserMgrPostService.class);
5、调用接口方法返回Call对象
retrofit2.Call call = service.getMessage(telNum);
6、发送请求(同步、异步)
同步: 调用Call的execute(),返回结果的响应体
异步: 调用Call的enqueue(),参数是一个回调
call.enqueue(new retrofit2.Callback() {
@Override
public void onResponse(retrofit2.Call call, retrofit2.Response response) {
Log.e("info","Retrofit POST请求成功结果"+response.body().getShowapi_res_code());
}
@Override
public void onFailure(retrofit2.Call call, Throwable t) {
}
});
7、处理返回数据
UserMgrGetService.java
public interface UserMgrGetService {
@GET("6-1")
Call getMessage(@Query("num") String num);
}
进行请求代码块:
private void RetrofitGet() {
//创建retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Const.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //设置适配器
.build();
//得到Service对象
UserMgrGetService service = retrofit.create(UserMgrGetService.class);
retrofit2.Call call = service.getMessage(telNum);
call.enqueue(new retrofit2.Callback() {
@Override
public void onResponse(retrofit2.Call call, retrofit2.Response response) {
Log.e("info","Retrofit Get请求成功结果"+response.body().getShowapi_res_code());
}
@Override
public void onFailure(retrofit2.Call call, Throwable t) {
}
});
}
UserMgrPostService.java
public interface UserMgrPostService {
@POST("6-1")
@FormUrlEncoded
Call getMessage(@Field("num") String num);
}
进行请求代码块:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Const.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
UserMgrPostService service = retrofit.create(UserMgrPostService.class);
retrofit2.Call call = service.getMessage(telNum);
call.enqueue(new retrofit2.Callback() {
@Override
public void onResponse(retrofit2.Call call, retrofit2.Response response) {
Log.e("info","Retrofit POST请求成功结果"+response.body().getShowapi_res_code());
}
@Override
public void onFailure(retrofit2.Call call, Throwable t) {
}
});
https://download.csdn.net/download/qi85481455/10709907