OkHttpClientUtils.java文件code:
package com.example.kaiqigu.myapplication;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Iterator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpClientUtils {
private final StringTAG="OkHttpClientUtils";
//创建okHttpClient对象
private static OkHttpClient mOkHttpClient =null;//网络请求对象
private static OkHttpClientUtilsOkHttpClientUtils =null;//类对象
//单例模式
public static OkHttpClient getInstance(){
if (mOkHttpClient==null){
mOkHttpClient=new OkHttpClient();
}
return mOkHttpClient;
}
//get异步请求
public void getData(String url, JSONObject JSONObject) {
if (JSONObject !=null) {
Iterator iterator = JSONObject.keys();
StringBuilder stringBuilder =new StringBuilder();
stringBuilder.append("/?");
while (iterator.hasNext()) {
String key = iterator.next();
try {
stringBuilder.append(key+"=");
stringBuilder.append(JSONObject.get(key)+"&");
}catch (JSONException e) {
e.printStackTrace();
}
}
stringBuilder.delete(stringBuilder.length()-1,stringBuilder.length());
String url1 = url + stringBuilder.toString();
Request request =new Request.Builder()
.url(url1)
.build();
Call call =mOkHttpClient.newCall(request);
// call.execute(new Call);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "网络请求失败!!!");
}
@Override
public void onResponse(Call call, Response response)throws IOException {
String httpData = response.body().string();
Log.e("httpData------->", httpData);
Log.e("code------>", String.valueOf(response.code()));
}
});
}
}
//post异步请求
public void postData(String url, JSONObject JSONObject) {
if (JSONObject !=null) {
//传键值对参数
FormBody.Builder builder =new FormBody.Builder();
Iterator iterator = JSONObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
builder.add(key,JSONObject.get(key));
}catch (JSONException e) {
e.printStackTrace();
}
}
Request request =new Request.Builder()
.url(url)
.post(builder.build())
.build();
Call call =mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "网络请求失败!!!");
}
@Override
public void onResponse(Call call, Response response)throws IOException {
if (response.isSuccessful()) {
String httpData = response.body().string();
Log.e("httpData------->", httpData);
Log.e("code---->", String.valueOf(response.code()));
}
}
});
}
}
}