1.在build.gradle引入okhttp3依赖
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okio:okio:1.13.0'
2.在AndroidMainifest.xml加入网络请求权限
<uses-permission android:name="android.permission.INTERNET" />
创建Okhttp3工具类
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class OKHttpUtil {
private OkHttpClient instance;
//1.私有化构造函数
private OKHttpUtil() {
//2.使用DCL模式单例模式
if (null == instance) {
synchronized (OKHttpUtil.class) {
if (null == instance) {
instance = new OkHttpClient();
}
}
}
}
public static OKHttpUtil getInstance() {
OKHttpUtil instance = null;
//2.使用DCL模式单例模式
if (null == instance) {
synchronized (OKHttpUtil.class) {
if (null == instance) {
instance = new OKHttpUtil();
}
}
}
return instance;
}
//封装get请求
public void get(String urlString,FormBody formBody, Callback callback){
Request request = new Request.Builder().url(urlString).build();
instance.newCall(request).enqueue(callback);
}
//封装post请求
public void post(String urlString, FormBody formBody, Callback callback){
Request request = new Request.Builder().method("POST",formBody).url(urlString).build();
instance.newCall(request).enqueue(callback);
}
}
// FormBody formBody = new FormBody.Builder()
// .add("mobile", username)
// .add("password", password)
// .build();
使用案例,本地服务要用Ip地址,localhost访问不到本机
class login implements View.OnClickListener{
@Override
public void onClick(View v) {
if(v.getId()==R.id.button3)
{
OKHttpUtil.getInstance().get("http://192.168.31.168:8080/login", null, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Loger.debug("eerror");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText=response.body().string();
Loger.debug("请求到的数据:" + responseText);
}
});
}
}
}