use of com.lzy.demo.model.LzyResponse in project okhttp-OkGo by jeasonlzy.
the class UpActivity method upJson.
@OnClick(R.id.upJson)
public void upJson(View view) {
HashMap<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "这里是需要提交的json格式数据");
params.put("key3", "也可以使用三方工具将对象转成json字符串");
params.put("key4", "其实你怎么高兴怎么写都行");
JSONObject jsonObject = new JSONObject(params);
//
OkGo.<LzyResponse<ServerModel>>post(Urls.URL_TEXT_UPLOAD).tag(//
this).headers("header1", //
"headerValue1").upJson(//
jsonObject).execute(new DialogCallback<LzyResponse<ServerModel>>(this) {
@Override
public void onSuccess(Response<LzyResponse<ServerModel>> response) {
handleResponse(response);
}
@Override
public void onError(Response<LzyResponse<ServerModel>> response) {
handleError(response);
}
});
}
use of com.lzy.demo.model.LzyResponse in project okhttp-OkGo by jeasonlzy.
the class JsonConvert method parseParameterizedType.
private T parseParameterizedType(Response response, ParameterizedType type) throws Exception {
if (type == null)
return null;
ResponseBody body = response.body();
if (body == null)
return null;
JsonReader jsonReader = new JsonReader(body.charStream());
// 泛型的实际类型
Type rawType = type.getRawType();
// 泛型的参数
Type typeArgument = type.getActualTypeArguments()[0];
if (rawType != LzyResponse.class) {
// 泛型格式如下: new JsonCallback<外层BaseBean<内层JavaBean>>(this)
T t = Convert.fromJson(jsonReader, type);
response.close();
return t;
} else {
if (typeArgument == Void.class) {
// 泛型格式如下: new JsonCallback<LzyResponse<Void>>(this)
SimpleResponse simpleResponse = Convert.fromJson(jsonReader, SimpleResponse.class);
response.close();
// noinspection unchecked
return (T) simpleResponse.toLzyResponse();
} else {
// 泛型格式如下: new JsonCallback<LzyResponse<内层JavaBean>>(this)
LzyResponse lzyResponse = Convert.fromJson(jsonReader, type);
response.close();
int code = lzyResponse.code;
// 一般来说服务器会和客户端约定一个数表示成功,其余的表示失败,这里根据实际情况修改
if (code == 0) {
// noinspection unchecked
return (T) lzyResponse;
} else if (code == 104) {
throw new IllegalStateException("用户授权信息无效");
} else if (code == 105) {
throw new IllegalStateException("用户收取信息已过期");
} else {
// 直接将服务端的错误信息抛出,onError中可以获取
throw new IllegalStateException("错误代码:" + code + ",错误信息:" + lzyResponse.msg);
}
}
}
}
Aggregations