package com.xxx.utils;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttp3Utils<T> {
public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
private static final MediaType URLENCODED=MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");
private OkHttpClient myOkHttpClient;
//回调接口
public interface AnsyCallback<T> {
public void AnsyLoader(int what,T loder);
}
//get、post封装方法
public void get(final String url,final AnsyCallback<T> ansyCallback){
sendRequestWithOkHttp( url,null,ansyCallback,URLENCODED);
}
public void post(final String url,String body,final AnsyCallback<T> ansyCallback){
sendRequestWithOkHttp( url,body,ansyCallback,URLENCODED);
}
/**
* 将Map<String, String> 转换为 name=value&name=value 形式的字符串
* @param map
* @return
*/
public static String map2NamVal(Map<String, String> map){
StringBuilder str = new StringBuilder();
Set<String> set = map.keySet();
for (String key : set) {
str.append(key).append("=").append(map.get(key)).append("&");
}
return str.toString().substring(0, str.lastIndexOf("&"));
}
/**
* @param url 访问链接
* @param body 请求参数
* @param ansyCallback 回调接口
* @param mime MIME类型
*/
private void sendRequestWithOkHttp(final String url,String body,
final AnsyCallback<T> ansyCallback,MediaType mime){
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
ansyCallback.AnsyLoader(msg.what,(T)msg.obj);
}
};
myOkHttpClient = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url(url);
Request request;
if (body != null) {
RequestBody requestBody = RequestBody.create(mime,body);
System.out.printf("******body*%s%s*******",mime,body);
request = requestBuilder.post(requestBody).build();
} else {
request = requestBuilder.get().build();
}
Call mycall = myOkHttpClient.newCall(request);
// 发送异步请求
mycall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = handler.obtainMessage(0,e.getStackTrace());
handler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("请求失败: " + response.body().toString());
}else {
if (null != response.cacheResponse()) {
String data = response.cacheResponse().toString();
handler.sendMessage(handler.obtainMessage(1, data));
System.out.println("****print****"+data);
Log.i("****Request****", "cache---" + data);
} else {
String data = response.body().string();
String str = response.networkResponse().toString();
Message message = handler.obtainMessage(1, data);
handler.sendMessage(message);
System.out.println("****print****"+data);
Log.i("****Request****", "network---" + str);
}
}
}
});
}
}
OkHttp3Utils<String> okHttp3 = new OkHttp3Utils<>();
Map<String, String> map=new HashMap<>();
map.put("username",id.getText().toString());
map.put("password", passwd.getText().toString());
map.put("isMax","false");
String databody=okHttp3.map2NamVal(map);
okHttp3.post(loginUrl,databody, new OkHttp3Utils.AnsyCallback<String>() {
@Override
public void AnsyLoader(int what,String loder) {
try {
JSONObject obj = new JSONObject(loder);
if("1".equals(obj.get("status").toString())) {
Intent intent = new Intent(StartActivity.this, Demo3ActivityWithFragment.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});