android 使用Okhttp封装上传JSON格式工具类
public class PostRequestJSON_Util {
private static PostRequestJSON_Util postRequestJSONUtil;
private Handler mHandler = new Handler(Looper.getMainLooper());
public static PostRequestJSON_Util getInstance() {
if (postRequestJSONUtil == null) {
postRequestJSONUtil = new PostRequestJSON_Util();
}
return postRequestJSONUtil;
}
// map集合,需要上传的josn数据
public void postJson(String url, Map<Object, Object> map, setResponseListener mListener) {
String jsonStr = new Gson().toJson(map);
RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonStr);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (mListener != null) {
mHandler.post(new Runnable() { //使用handler切换到主线程更新UI
@Override
public void run() {
try {
mListener.onFailers(e.getMessage()); //接口回调失败方法
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
if (mListener != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
mListener.onSuccessful(response); //接口回调成功方法
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
});
}
public interface setResponseListener {
void onSuccessful(Response response);
void onFailers(String str);
}
}
使用如下:
// String URL = "https://api.test.ndmooc.com/v1/digitalmeet/add?token=9dbeb5da0d7372596e363a9383ea91aff855f18d";
String URL = API.apiurl() + "v1/digitalmeet/add?token=" + token;
HashMap<Object, Object> map = new HashMap<>();
map.put("mynotebooks_id", mynotebook_id);
map.put("title", mTvMeetTitle.getText().toString());
if (mTvType.getText().toString().equals("会议")) {
map.put("type", "1");
} else if (mTvType.getText().toString().equals("学习")) {
map.put("type", "2");
}
PostRequestJSON_Util.getInstance().postJson(URL, map, new PostRequestJSON_Util.setResponseListener() {
@Override
public void onSuccessful(Response response) {
try {
progressDialog.dismiss();
String string = response.body().string();
NewBuildBean buildBean = new Gson().fromJson(string, NewBuildBean.class);
digitalmeet_id = buildBean.getData().getDigitalmeet_id();
startActivity(new Intent(NewBuildMeetActivity.this, MeetingMessageActivity.class).putExtra("digitalmeet_id",
digitalmeet_id).putExtra("mynotebook_id",
mynotebook_id).putExtra("notebook_id", notebook_id));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailers(String str) {
Log.i(TAG, "onFailers: " + str);
}
});