此demo使用了
okhttputils---网络请求,butterknife---控件快捷,gson解析
主要文件如下图
MVC模式模式主要文件分别是MainActivity(M),布局文件(V),MvcListen、MvcModel、MvcModelImp(C),下面分别按编码顺序说明demo
1、MvcListen
public interface MvcListener { void onSuccess(String str); void onFailed(); }定义监听接口,包含成功和失败2个方法,成功方法用来传递下载的JSON数据
2、MvcModel
public interface MvcModel { void getHttpInfo(Map<String,String> params,String url,MvcListener mvcListener); }定义实现接口,用于网络请求
3、MvcModelImp
public class MvcModelImp implements MvcModel{ @Override public void getHttpInfo(Map<String, String> params, String url, final MvcListener mvcListener) { FormBody.Builder builder = new FormBody.Builder(); //遍历集合,,,map集合遍历方式 for (String key : params.keySet()) { builder.add(key, params.get(key)); } OkHttpUtils .get() .url(url) .params(params) .build() .execute(new StringCallback() { @Override public void onError(okhttp3.Call call, Exception e, int id) { mvcListener.onFailed(); } @Override public void onResponse(String response, int id) { Log.e("response===",response); mvcListener.onSuccess(response); } }); } }类文件实现 MvcModel接口,因为接口没办法实例化
4、下面是布局文件(一个button一个textview的简单布局)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.sf.mvc.activity.MainActivity" android:orientation="vertical"> <Button android:id="@+id/btn_summit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请求数据"/> <TextView android:id="@+id/tv_str" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </LinearLayout>
5、下面是MainActity,主要用于view展现以及点击操作
public class MainActivity extends Activity implements MvcListener { @Bind(R.id.tv_str) TextView tvStr; @Bind(R.id.btn_summit) Button btnSummit; private MvcModel weatherModel; private Map<String, String> loginMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); weatherModel = new MvcModelImp(); loginMap = new HashMap<String, String>(); } private String url = Common.URL + "/login?"; @OnClick(R.id.btn_summit) public void onViewClicked() { loginMap.put("uName", "盛飞"); loginMap.put("password", "123456"); weatherModel.getHttpInfo(loginMap, url, MainActivity.this); } @Override public void onSuccess(String str) { //这里可以解析网络请求的str成对象,以防报错加入try-catch // MvcBean mvcBean=null; // try { // mvcBean=GsonUtils.jsonTobean(str,MvcBean.class);; // }catch (Exception e){ // // } tvStr.setText(str); }@Override public void onFailed() { Toast.makeText(MainActivity.this,"登录失败",Toast) }}
在这里通过MVC模式实现了简单的登录的网络请求功能
源码下载地点击打开demo