Okhttputils
车嘉实
2023-12-01
package com.example.lenovo.jd.view.utils;
import android.os.Handler;
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 lenovo on 2018/2/27.
*/
public class OkHttpUtils {
private static OkHttpUtils OK_HTTP_UTILS = null;
private Handler handler = new Handler();
private OkHttpUtils() {}
public static OkHttpUtils getIndata(){
if (OK_HTTP_UTILS == null){
synchronized (OkHttpUtils.class){
if (OK_HTTP_UTILS == null){
OK_HTTP_UTILS = new OkHttpUtils();
}
}
}
return OK_HTTP_UTILS;
}
public void doGet(String path, Map<String,String> map, final OnFinishListener onFinishListener){
StringBuffer sb = new StringBuffer();
sb.append(path);
if (sb.indexOf("?") != -1){
if (sb.indexOf("?") != sb.length()-1){
sb.append("&");
}
}else {
sb.append("?");
}
for (Map.Entry<String,String> m : map.entrySet()) {
sb.append(m.getKey())
.append("=")
.append(m.getValue())
.append("&");
}
if (sb.lastIndexOf("&") != -1){
sb.deleteCharAt(sb.length()-1);
}
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url(sb.toString())
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onFailed(e.getMessage());
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response.isSuccessful()){
final String result = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onSuccess(result);
}
});
}else {
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onFailed(response.message());
}
});
}
}
});
}
public void doPost(String path, Map<String,String> map, final OnFinishListener onFinishListener){
OkHttpClient okHttpClient = new OkHttpClient();
FormBody.Builder body = new FormBody.Builder();
for (String key : map.keySet()) {
body.add(key,map.get(key));
}
Request request = new Request.Builder()
.post(body.build())
.url(path)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onFailed(e.getMessage());
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response.isSuccessful()){
final String result = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onSuccess(result);
}
});
}else {
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onFailed(response.message());
}
});
}
}
});
}
}