一:定义一个接口里面有请求成功与失败的方法
public interface CallBack {
void onSuccess(Object o);
void onFailed(Exception e);
}
二:工具类中
package activity.example.com.httputils;
import android.os.Handler;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by 壹颗大金星 on 2017/11/9.
*/
public class HttpUtils {
private static volatile HttpUtils instance;
private static Handler handler = new Handler();
private HttpUtils(){
}
public static HttpUtils getInstance() {
if (instance == null) {
synchronized (HttpUtils.class) {
if (instance == null) {
instance = new HttpUtils();
}
}
}
return instance;
}
//get请求
public void get(String url, Map<String,String> map, final CallBack callBack, final Class c){
//对url和参数做拼接处理
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(url);
//判断是否存在? if中是存在
if(stringBuffer.indexOf("?")!=-1 ){
//判断?是否在最后一位 if中是不在最后一位
if(stringBuffer.indexOf("?")!=stringBuffer.length()-1){
stringBuffer.append("&");
}
}else{
stringBuffer.append("?");
}
for(Map.Entry<String,String> entry:map.entrySet()){
stringBuffer.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
//判断是否存在& if中是存在
if(stringBuffer.indexOf("&")!=-1){
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("&"));
}
//1:创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2:创建Request对象
final Request request = new Request.Builder()
.get()
.url(stringBuffer.toString())
.build();
//3:创建Call对象
Call call = okHttpClient.newCall(request);
//4:请求网络
call.enqueue(new Callback() {
//请求失败
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.onFailed(e);
}
});
}
//请求成功
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
//拿到数据解析
final Object o = new Gson().fromJson(result, c);
//当前是在子线程,回到主线程中
handler.post(new Runnable() {
@Override
public void run() {
//回调
callBack.onSuccess(o);
}
});
}
});
}
//post请求
public void post(String url, Map<String,String> map, final CallBack callBack, final Class c){
//1:创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2:提供post请求需要的body对象
FormBody.Builder builder = new FormBody.Builder();
for(Map.Entry<String,String> entry:map.entrySet()){
builder.add(entry.getKey(),entry.getValue());
}
FormBody body = builder.build();
//3:创建Request对象
final Request request = new Request.Builder()
.post(body)
.url(url)
.build();
//4:创建Call对象
Call call = okHttpClient.newCall(request);
//5:请求网络
call.enqueue(new Callback() {
//请求失败
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.onFailed(e);
}
});
}
//请求成功
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
//拿到数据解析
final Object o = new Gson().fromJson(result, c);
//当前是在子线程,回到主线程中
handler.post(new Runnable() {
@Override
public void run() {
//回调
callBack.onSuccess(o);
}
});
}
});
}
}
三:MainActivity引用
package activity.example.com.httputils;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private Button get;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
get = (Button)findViewById(R.id.get);
text = (TextView)findViewById(R.id.text);
get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Map<String,String> map = new HashMap<String, String>();
map.put("mobile","00000000000");
map.put("password","123456");
HttpUtils.getInstance().get("http://120.27.23.105/user/login", map,
new CallBack() {
@Override
public void onSuccess(Object o) {
//o请求回来的数据,已经解析完
final User user = (User)o;
//请求出来的数据展示到textview上
text.setText(user.getMsg());
}
@Override
public void onFailed(Exception e) {
}
},User.class);//最后一个参数是解析的实体类
}
});
}
}