项目要求用json提交参数,以前在网上找的别的大神(忘了是谁)封装的NetUtils工具不适应了,在网上也没找到适合的,就自己修改了一下,
根据restful设计风格,支持
GET 查询
PUT 更新
POST 新增
DELETE 删除
自用记录一下。
完整代码
/**
* Created by wxz on 2018/8/27.
*/
public class NetUtils {
private static final byte[]LOCKER =new byte[0];
private static NetUtilsmInstance;
private OkHttpClientmOkHttpClient;
private GsonmGson =new Gson();
private NetUtils() {
okhttp3.OkHttpClient.Builder ClientBuilder=new okhttp3.OkHttpClient.Builder();
ClientBuilder.readTimeout(20, TimeUnit.SECONDS);//读取超时
ClientBuilder.connectTimeout(10, TimeUnit.SECONDS);//连接超时
ClientBuilder.writeTimeout(60, TimeUnit.SECONDS);//写入超时
//支持HTTPS请求,跳过证书验证
ClientBuilder.sslSocketFactory(createSSLSocketFactory());
ClientBuilder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
mOkHttpClient=ClientBuilder.build();
}
/**
* 单例模式获取NetUtils
* @return
*/
public static NetUtilsgetInstance() {
if (mInstance ==null) {
synchronized (LOCKER) {
if (mInstance ==null) {
mInstance =new NetUtils();
}
}
}
return mInstance;
}
/**
* get请求,同步方式,获取网络数据,是在主线程中执行的,需要新起线程,将其放到子线程中执行
* @param url
* @return
*/
public ResponsegetDataSynFromNet(String url) {
//1 构造Request
Request.Builder builder =new Request.Builder();
Request request=builder.get().url(url).build();
//2 将Request封装为Call
Call call =mOkHttpClient.newCall(request);
//3 执行Call,得到response
Response response =null;
try {
response = call.execute();
}catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* post请求,同步方式,提交数据,是在主线程中执行的,需要新起线程,将其放到子线程中执行
* @param url
* @param bodyParams
* @return
*/
public ResponsepostDataSynToNet(String url,Map bodyParams) {
//1构造RequestBody
RequestBody body=setRequestBody(bodyParams);
//2 构造Request
Request.Builder requestBuilder =new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
// request = requestBuilder.delete()
//3 将Request封装为Call
Call call =mOkHttpClient.newCall(request);
//4 执行Call,得到response
Response response =null;
try {
response = call.execute();
}catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* get下载图片
* @param url
* @param imagePath 图片路径
* @return byte[]
* @throws IOException
*/
public static byte[]downloadImage(String url, String imagePath)throws IOException {
OkHttpClient okHttpClient =new OkHttpClient();
Request request =new Request.Builder()
.url(url+"/show?fileName="+imagePath)
.build();
Response response = okHttpClient.newCall(request).execute();
byte[] bytes = response.body().bytes();
return bytes;
}
/**
* post请求上传文件....包括图片....流的形式传任意文件...
* 参数1 url
* file表示上传的文件
* fileName....文件的名字,,例如aaa.jpg
* params ....传递除了file文件 其他的参数放到map集合
*
*/
public void uploadFile(String url, File file, String fileName, Map
params,final MyNetCall myNetCall) {
//创建OkHttpClient请求对象
//MultipartBody多功能的请求实体对象,,,formBody只能传表单形式的数据
MultipartBody.Builder builder =new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
//参数
if (params !=null){
for (String key : params.keySet()){
builder.addFormDataPart(key,params.get(key));
}
}
//文件...参数name指的是请求路径中所接受的参数...如果路径接收参数键值是fileeeee,
//此处应该改变
builder.addFormDataPart("file",fileName,RequestBody.create
(MediaType.parse("application/octet-stream"),file));
//构建
MultipartBody multipartBody = builder.build();
//创建Request
Request request =new Request.Builder().url(url).post(multipartBody).build();
//得到Call
Call call =mOkHttpClient.newCall(request);
//执行请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call,e);
}
@Override
public void onResponse(Call call, Response response)throws IOException {
myNetCall.success(call,response);
}
});
}
/**
* 自定义网络回调接口
*/
public interface MyNetCall{
void success(Call call, Response response)throws IOException;
void failed(Call call, IOException e);
}
/**
* get请求,异步方式,获取网络数据,是在子线程中执行的,需要切换到主线程才能更新UI
* @param url
* @param myNetCall
* @return
*/
public void getDataAsynFromNet(String url, final MyNetCall myNetCall) {
//1 构造Request
Request.Builder builder =new Request.Builder();
Request request=builder.get().url(url).build();
//2 将Request封装为Call
Call call =mOkHttpClient.newCall(request);
//3 执行Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call,e);
}
@Override
public void onResponse(Call call, Response response)throws IOException {
myNetCall.success(call,response);
}
});
}
/**
* post请求,异步方式,提交数据,是在子线程中执行的,需要切换到主线程才能更新UI
* @param url
* @param bodyParams
* @param myNetCall
*/
public void postDataAsynToNet(String url, Map bodyParams, final MyNetCall myNetCall) {
// String params = mGson.toJson(bodyParams);
// MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// RequestBody body = RequestBody.create(JSON, params);
//1构造RequestBody
RequestBody body=setRequestBody(bodyParams);
//2 构造Request
Request.Builder requestBuilder =new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
//3 将Request封装为Call
Call call =mOkHttpClient.newCall(request);
//4 执行Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call,e);
}
@Override
public void onResponse(Call call, Response response)throws IOException {
myNetCall.success(call,response);
}
});
}
/**
* post的请求参数,构造RequestBody
* @param BodyParams
* @return
*/
private RequestBodysetRequestBody(Map BodyParams){
String params =mGson.toJson(BodyParams);
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body=null;
// okhttp3.FormBody.Builder formEncodingBuilder=new okhttp3.FormBody.Builder();
if(BodyParams !=null){
body = RequestBody.create(JSON, params);
// Iterator iterator = BodyParams.keySet().iterator();
// String key = "";
// while (iterator.hasNext()) {
// key = iterator.next().toString();
// formEncodingBuilder.add(key, BodyParams.get(key));
// Log.d("post http", "post_Params==="+key+"===="+BodyParams.get(key));
// }
}
return body;
}
/**
* put,同步方式,提交数据,是在主线程中执行的,需要新起线程,将其放到子线程中执行
* @param url
* @param bodyParams
* @return
*/
public ResponseputDataSynToNet(String url,Map bodyParams) {
//1构造RequestBody
RequestBody body=setRequestBody(bodyParams);
//2 构造Request
Request.Builder requestBuilder =new Request.Builder();
Request request = requestBuilder.put(body).url(url).build();
// request = requestBuilder.delete()
//3 将Request封装为Call
Call call =mOkHttpClient.newCall(request);
//4 执行Call,得到response
Response response =null;
try {
response = call.execute();
}catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* put请求,异步方式,提交数据,是在子线程中执行的,需要切换到主线程才能更新UI
* @param url
* @param bodyParams
* @param myNetCall
*/
public void putDataAsynToNet(String url, Map bodyParams, final MyNetCall myNetCall) {
//1构造RequestBody
RequestBody body=setRequestBody(bodyParams);
//2 构造Request
Request.Builder requestBuilder =new Request.Builder();
Request request = requestBuilder.put(body).url(url).build();
//3 将Request封装为Call
Call call =mOkHttpClient.newCall(request);
//4 执行Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call,e);
}
@Override
public void onResponse(Call call, Response response)throws IOException {
myNetCall.success(call,response);
}
});
}
/**
* Delete,同步方式,提交数据,是在主线程中执行的,需要新起线程,将其放到子线程中执行
* @param url
* @param bodyParams
* @return
*/
public ResponsedeleteDataSynToNet(String url,Map bodyParams) {
//1构造RequestBody
RequestBody body=setRequestBody(bodyParams);
//2 构造Request
Request.Builder requestBuilder =new Request.Builder();
Request request = requestBuilder.delete(body).url(url).build();
// request = requestBuilder.delete()
//3 将Request封装为Call
Call call =mOkHttpClient.newCall(request);
//4 执行Call,得到response
Response response =null;
try {
response = call.execute();
}catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* Delete请求,异步方式,提交数据,是在子线程中执行的,需要切换到主线程才能更新UI
* @param url
* @param bodyParams
* @param myNetCall
*/
public void deleteDataAsynToNet(String url, Map bodyParams, final MyNetCall myNetCall) {
//1构造RequestBody
RequestBody body=setRequestBody(bodyParams);
//2 构造Request
Request.Builder requestBuilder =new Request.Builder();
Request request = requestBuilder.delete(body).url(url).build();
//3 将Request封装为Call
Call call =mOkHttpClient.newCall(request);
//4 执行Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call,e);
}
@Override
public void onResponse(Call call, Response response)throws IOException {
myNetCall.success(call,response);
}
});
}
/**
* 判断网络是否可用
* @param context
* @return
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm ==null) {
}else {
//如果仅仅是用来判断网络连接
//则可以使用cm.getActiveNetworkInfo().isAvailable();
NetworkInfo[] info = cm.getAllNetworkInfo();
if (info !=null) {
for (int i =0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
/**
* 生成安全套接字工厂,用于https请求的证书跳过
* @return
*/
public SSLSocketFactorycreateSSLSocketFactory() {
SSLSocketFactory ssfFactory =null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
ssfFactory = sc.getSocketFactory();
}catch (Exception e) {
}
return ssfFactory;
}
/**
* 用于信任所有证书
*/
class TrustAllCertsimplements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)throws CertificateException {
}
@Override
public X509Certificate[]getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
使用,写了一个小demo
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
et1 = findViewById(R.id.et1);
et2 = findViewById(R.id.et2);
et3 = findViewById(R.id.et3);
iv = findViewById(R.id.iv);
}
public void main(View view) {
switch (view.getId()){
case R.id.button:
//构造请求参数
Map reqBody =new ConcurrentSkipListMap<>();
reqBody.put("loginName", et1.getText().toString());
reqBody.put("password", et2.getText().toString());
//获取网络请求工具类实例
NetUtils netUtils = NetUtils.getInstance();
netUtils.postDataAsynToNet(MIAN +LOGIN, reqBody, new NetUtils.MyNetCall() {
@Override
public void success(Call call, Response response)throws IOException {
result = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(result);
}
});
}
@Override
public void failed(Call call, IOException e) {
tv.setText("失败");
}
});
break;
case R.id.button1:
//构造请求参数
Map reqBody1 =new ConcurrentSkipListMap<>();
reqBody1.put("loginName", et1.getText().toString());
reqBody1.put("password", et2.getText().toString());
reqBody1.put("confirmPwd", et3.getText().toString());
reqBody1.put("userEmail", "");
reqBody1.put("userMobile", "AAAA");
reqBody1.put("userName", "AAAA");
reqBody1.put("userType", "0");
//获取网络请求工具类实例
NetUtils netUtils1 = NetUtils.getInstance();
netUtils1.postDataAsynToNet(MIAN +REGISTER, reqBody1, new NetUtils.MyNetCall() {
@Override
public void success(Call call, Response response)throws IOException {
result = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(result);
}
});
}
@Override
public void failed(Call call, IOException e) {
}
});
break;
case R.id.button2:
//构造请求参数
Map reqBody2 =new ConcurrentSkipListMap<>();
reqBody2.put("verifySign", et1.getText().toString());
reqBody2.put("verifyValue", et2.getText().toString());
//获取网络请求工具类实例
NetUtils netUtils2 = NetUtils.getInstance();
netUtils2.postDataAsynToNet(MIAN +SIGN_VERIFY_CODE, reqBody2, new NetUtils.MyNetCall() {
@Override
public void success(Call call, Response response)throws IOException {
result = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(result);
}
});
}
@Override
public void failed(Call call, IOException e) {
tv.setText("失败");
}
});
break;
case R.id.button3:
//获取网络请求工具类实例
NetUtils netUtils3 = NetUtils.getInstance();
netUtils3.getDataAsynFromNet(MIAN +VERIFY_CODE, new NetUtils.MyNetCall() {
@Override
public void success(Call call, Response response)throws IOException {
result = response.body().string();
JSONObject jsonObject =null;
try {
jsonObject =new JSONObject(result);
data = jsonObject.getString("data");
jsonObject =new JSONObject(data);
verifyImageStr = jsonObject.getString("verifyImageStr");
}catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "run: "+result);
iv.setImageBitmap(Base64ImgUtilis.stringtoBitmap(verifyImageStr));
tv.setText(result);
}
});
}
@Override
public void failed(Call call, IOException e) {
tv.setText("失败");
}
});
break;
}
}