retrofit_okhttp
public class Model {
//使用前提:必须添加4个依赖库
Retrofit retrofit;
//服务器地址
public static final String BASE_URL = "http://....com";
public static final String ID = "44297";
public static final String SIGN = "cc8738fb83254674b4b1e169548ce8b9";
//回调接口,通知”外面“,里面接口调用抽象方法。外面实现该接口
public interface BeanCallback<T> {
void onSuccess(T bean);
void onError(String message);
}
/**单例模式**/
private Model() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create())
//请求bean对象
//请求String则是ScalarsConverterFactory
.build();
}
private static Model instance= new Model();
public static Model getInstance() {
return instance;
}
//请求接口
public void getType(final BeanCallback<第一次先写String,第二次写Bean> callback) {
//使用retorfit请求接口
Call<分两次> call = retrofit.create(接口注解.class).getType(ID, SIGN);
call.enqueue(new Callback<分两次>() {
@Override
public void onResponse(Call<分两次> call, Response<分两次> response) {
//第一次
//Log.e("TAG", "--------" + response.body().toString());
//第二次(如果是JsonObject系统自动转)
TypeBean bean = response.body();
/**如果是JsonArray,自己手动转
Gson gson = new Gson();
String result = response.body();
List<bean> list = gson.fromJson(result, new TypeToken<List<bean>>() {}.getType());**/
if (bean.getShowapi_res_code() == 0)
callback.onSuccess(bean);
else
callback.onError(bean.getShowapi_res_error());
}
@Override
public void onFailure(Call<TypeBean> call, Throwable t) {
callback.onError("网络请求失败!");
}
});
}
两种模式:
MVC:单例.getType
MVP:new Presenter————–model通知presenter———-presenter通知ui
okhttp请求到数据,修改ui———必须runOnUiThread
retrofit请求到数据,直接修改Ui
/**接口注解**/
public interface GirlService {
//类型接口
String TYPE_URL = "/1208-1";
//根据ID 获取图片集
String PICLIST_BY_ID = "/1208-2";
//根据图片集 列举所有图片
String ALLPIC_BY_LIST = "/1208-3";
//http:
// 请求行 请求方法(GET POST) url http1.1
// 请求头 正文的格式 json,xml,键值对,流
// 请求正文
//GET请求 获取 类型接口
@GET(TYPE_URL)
//Get的参数 使用Query来标记
Call<TypeBean> getType(@Query("showapi_appid") String showApi_id, @Query("showapi_sign") String showApi_sign);
//使用Post来请求 根据类型id获取图片集
@POST(PICLIST_BY_ID) // @Multipart带文件 使用Part
// @FormUrlEncoded 不带文件使用Field
//标明 内容类型
@FormUrlEncoded
//使用键值对
Call<ListBean> getListByTypeId(@Field("showapi_appid") String showApi_id, @Field("showapi_sign") String showApi_sign,
@Field("type") int type, @Field("page") int page, @Field("rows") int rows);
@POST(ALLPIC_BY_LIST)
@FormUrlEncoded
Call<PicBean> getAllList(@Field("showapi_appid") String showApi_id, @Field("showapi_sign") String showApi_sign, @Field("id") String id);
// @POST("dizhi")
// @Multipart
// Call<String> test(@Part MultipartBody.Part file, @Part("username") String username, @Part("password") String password);
}
xutils
1. xutils 初始化
2. 设置请求参数 RequestParams
3. 开始请求 x.http().post