简单的实现联网登录与注册的功能,并展示可以切换展示模式的请求数

一.http包里的
1.HttpConfig(里面的接口根据需要自己定)


 
 
/** * 接口类 * 用于存放接口 * 存放需要用到的数据接口地址 */ public class HttpConfig {
//登录接口 public static String login_url = "http://120.27.23.105/user/login"; // 注册 public static String reg_url = "http://120.27.23.105/user/reg"; // 商品列表接口 public static String goods_list_url = "http://120.27.23.105/product/searchProducts"; }
2.OkLoadListener


 
 
/** * Created by lenovo on 2018/4/20.
*/ public interface OkLoadListener { //请求数据成功 void okLoadSuccess(String json); //请求数据失败 void okLoadError(String error); }
3.HttpUtils(工具包类,主要是做
封装ok  post 拦截器添加公共参数的)

 
 

public class HttpUtils { private static final String TAG = "HttpUtils-----"; private static HttpUtils httpUtils; private final int SUCCESS = 0; private final int ERROR = 1; private MyHandler myHandler = new MyHandler(); private OkLoadListener okLoadListener; public static HttpUtils getHttpUtils() { if ( httpUtils == null) { httpUtils = new HttpUtils(); } return httpUtils; } //Handler处理线程 class MyHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg. what) { case SUCCESS: //成功 String json = (String) msg. obj; okLoadListener.okLoadSuccess(json); break; case ERROR: //失败 String error = (String) msg. obj; okLoadListener.okLoadError(error); break; } } } //get public void okGet(String url) { OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor( new MyIntercepter()).build(); Request request = new Request.Builder().url(url).build(); Call call = okHttpClient.newCall(request); call.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Message message = myHandler.obtainMessage(); message. what = ERROR; message. obj = e.getMessage(); myHandler.sendMessage(message); } @Override public void onResponse(Call call, Response response) throws IOException { Message message = myHandler.obtainMessage(); message. what = SUCCESS; message. obj = response.body().string(); myHandler.sendMessage(message); } }); } public void setOkLoadListener(OkLoadListener okLoadListener) { this. okLoadListener = okLoadListener; } //post public void okPost(String url, Map<String, String> params) { OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor( new MyIntercepter()).build(); FormBody.Builder builder = new FormBody.Builder(); Set<String> keySet = params.keySet(); for (String key : keySet) { String value = params.get(key); builder.add(key, value); } FormBody formBody = builder.build(); Request request = new Request.Builder().url(url).post(formBody).build(); Call call = okHttpClient.newCall(request); call.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Message message = myHandler.obtainMessage(); message. what = ERROR; message. obj = e.getMessage(); myHandler.sendMessage(message); } @Override public void onResponse(Call call, Response response) throws IOException { Message message = myHandler.obtainMessage(); message. what = SUCCESS; message. obj = response.body().string(); myHandler.sendMessage(message); } }); } //拦截器 class MyIntercepter implements Interceptor { //intercept 拦截 @Override public Response intercept(Chain chain) throws IOException { //添加公共参数 //post 取出原来所有的参数,将之加到新的请求体里面。然后让请求去执行 Request request = chain.request(); //获取请求方法 String method = request.method(); if (method.equals( "GET")) { //---------------------------GET 拦截 //取出url地址 String url = request.url().toString(); //拼接公共参数 boolean contains = url.contains( "?"); if (contains) { url = url + "&source=android"; } else { url = url + "?source=android"; } Request request1 = request.newBuilder().url(url).build(); Response response = chain.proceed(request1); return response; } else if (method.equals( "POST")) { //---------------------POST 拦截 RequestBody body = request.body(); //请求体 if (body instanceof FormBody) { //创建新的请求体 FormBody.Builder newBuilder = new FormBody.Builder(); for ( int i = 0; i < ((FormBody) body).size(); i++) { String key = ((FormBody) body).name(i); String value = ((FormBody) body).value(i); newBuilder.add(key, value); } //添加公共参数 newBuilder.add( "source", "android"); FormBody newBody = newBuilder.build(); //创建新的请求体 Request request1 = request.newBuilder().post(newBody).build(); //去请求 Response response = chain.proceed(request1); return response; } } return null; } } //上传文件(图片) public void upLoadImage(String url, String path) { //url 要上传的地址。path 要上传的文件路径 //媒体类型 MediaType mediaType = MediaType. parse( "image/*"); //multipartbody MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody. FORM); File file = new File(path); MultipartBody multipartBody = builder.addFormDataPart( "file", file.getName(), RequestBody. create(mediaType, file)).build(); OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder().url(url).post(multipartBody).build(); Call call = okHttpClient.newCall(request); call.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Log. d( TAG, "上传失败0----: "); } @Override public void onResponse(Call call, Response response) throws IOException { Log. d( TAG, "上传成功: "); } }); } }
二.model包
//下面先上一些接口

1.LoginListener
 
  
/** * Created by lenovo on 2018/4/20. *登录监听的接口 */ public interface LoginListener { //成功时调用 void loginSuccess(String json); //失败时调用 void loginError(String error); }
2.RegListener
 
   
/** * Created by lenovo on 2018/4/20.
*注册监听的接口 */ public interface RegListener { //注册成功 void regSuccess(String json); //注册失败 void regError(String error); }
3.GoodsListListener


 
 
/** * Created by lenovo on 2018/4/21.
*获取数据监听的接口 */ public interface GoodsListListener { // 获取数据成功 void getDataSuccess(String json); //获取数据失败 void getDataError(String error); }
4.IModel
 
 
/** * Created by lenovo on 2018/4/20.
*/ public interface IModel { //登录 void login(String url, Map<String ,String> params,LoginListener loginListener); //注册 void reg(String url, Map<String, String> params, RegListener regListener); // 获取商品数据 void getGoodsListData(String url, Map<String, String> params, GoodsListListener goodsListListener); }
5.ModelImpl

 
 
public class ModelImpl implements IModel{ private static final String TAG = "ModelImpl----"; @Override public void login(String url, Map<String, String> params, final LoginListener loginListener) { //获取HttpUtils的工具类 HttpUtils httpUtils = HttpUtils. getHttpUtils(); //使用post请求 httpUtils.okPost(url,params); // 设置回调监听 httpUtils.setOkLoadListener( new OkLoadListener() { @Override public void okLoadSuccess(String json) { Log. d( TAG, "okLoadSuccess: "+json); Gson gson= new Gson(); UserBean userBean = gson.fromJson(json, UserBean. class); if(userBean.getCode().equals( "0")){ loginListener.loginSuccess(json); } else{ loginListener.loginError(json); } } @Override public void okLoadError(String error) { loginListener.loginError(error); } }); } @Override public void reg(String url, Map<String, String> params, final RegListener regListener) { //获取HttpUtils的工具类 HttpUtils httpUtils = HttpUtils. getHttpUtils(); //使用post请求 httpUtils.okPost(url,params); // 设置回调监听 httpUtils.setOkLoadListener( new OkLoadListener() { @Override public void okLoadSuccess(String json) { Log. d( TAG, "okLoadSuccess: "+json); Gson gson= new Gson(); RegBean userBean = gson.fromJson(json, RegBean. class); if(userBean.getCode().equals( "0")){ regListener.regSuccess(json); } else{ regListener.regError(json); } } @Override public void okLoadError(String error) { regListener.regError(error); } }); } @Override public void getGoodsListData(String url, Map<String, String> params, final GoodsListListener goodsListListener) { //获取HttpUtils的工具类 HttpUtils httpUtils = HttpUtils. getHttpUtils(); //使用post请求 httpUtils.okPost(url,params); // 设置回调监听 httpUtils.setOkLoadListener( new OkLoadListener() { @Override public void okLoadSuccess(String json) { Log. d( TAG, "okLoadSuccess: "+json); Gson gson= new Gson(); GoosListBean userBean = gson.fromJson(json, GoosListBean. class); if(userBean.getCode().equals( "0")){ goodsListListener.getDataSuccess(json); } else{ goodsListListener.getDataError(json); } } @Override public void okLoadError(String error) { goodsListListener.getDataError(error); } }); } }
6.MyAdapter (总共有两个,用以实现点击切换不同的模式,只要更改一下对应的布局即可)
 
  
 
  
public class MyAdapter extends BaseAdapter{ private Context context; private List<GoosListBean.DataBean> list; public MyAdapter(Context context, List<GoosListBean.DataBean> list) { this. context = context; this. list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem( int position) { return null; } @Override public long getItemId( int position) { return 0; } @Override public View getView( int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView == null){ convertView = View. inflate( context, R.layout. item_layout, null); ImageView imageView = (ImageView) convertView.findViewById(R.id. item_pic); TextView textView = (TextView) convertView.findViewById(R.id. item_title); holder = new ViewHolder(imageView,textView); convertView.setTag(holder); } else{ holder = (ViewHolder) convertView.getTag(); } //赋值 String images = list.get(position).getImages(); //拆分图片地址 String pic_url = images.split( " \\ |")[ 0]; //并将拆分后的地址赋给holder Glide. with( context).load(pic_url).into(holder.getImageView()); holder.getTextView().setText( list.get(position).getTitle()); return convertView; } class ViewHolder{ private ImageView imageView; private TextView textView; public ViewHolder(ImageView imageView, TextView textView) { this. imageView = imageView; this. textView = textView; } public ImageView getImageView() { return imageView; } public void setImageView(ImageView imageView) { this. imageView = imageView; } public TextView getTextView() { return textView; } public void setTextView(TextView textView) { this. textView = textView; } } }
6.5 item_layout(相应的也有两个,另一个只要将 orientation更改为horizontal即可)
 
  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/item_pic"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:singleLine="true"
        android:id="@+id/item_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="商品名" />

</LinearLayout>

7.然后是一些解析的(登录、注册和总的数据)Bean包,这里就不展示了

       三.presenter
      1.Ipresenter
 
 
public interface Ipresenter { // 登录 void loginPresenter(IModel iModel, IMainView iMainView); //注册 void regPresenter(IModel iModel, IRegView iRegView); // 显示数据 void showGoodsListToView(IModel iModel, IGoodsListView iGoodsListView); }
2.Presenter

 
 
public class Presenter implements Ipresenter{ private static final String TAG = "Presenter-----"; //登录 @Override public void loginPresenter(IModel iModel, final IMainView iMainView) { //调用m请求数据 Map<String,String> map = new HashMap<>(); //将手机号与密码存入集合中 map.put( "mobile", iMainView.getMobile()); map.put( "password", iMainView.getPassword()); iModel.login(HttpConfig. login_url, map, new LoginListener() { @Override public void loginSuccess(String json) { iMainView.loginSuccess(); } @Override public void loginError(String error) { iMainView.loginError(); } }); } //注册 @Override public void regPresenter(IModel iModel, final IRegView iRegView) { //调用m请求数据 Map<String,String> map = new HashMap<>(); //将手机号与密码存入集合中 map.put( "mobile", iRegView.getMobile()); map.put( "password", iRegView.getPassword()); iModel.reg(HttpConfig. reg_url, map, new RegListener(){ @Override public void regSuccess(String json) { iRegView.regSuccess(); } @Override public void regError(String error) { iRegView.regError(); } }); } @Override public void showGoodsListToView(IModel iModel, final IGoodsListView iGoodsListView) { //调用m请求数据 Map<String, String> map = new HashMap<>(); //将手机号与密码存入集合中 map.put( "keywords", "笔记本"); map.put( "page", "1"); iModel.getGoodsListData(HttpConfig. goods_list_url, map, new GoodsListListener() { @Override public void getDataSuccess(String json) { Gson gson= new Gson(); GoosListBean goosListBean = gson.fromJson(json, GoosListBean. class); iGoodsListView.showGoodsList(goosListBean.getData()); } @Override public void getDataError(String error) { Log. d( TAG, "失败---"); } }); } }
四.view

   1.IMainView
 
  
/** * 登录接口 */ public interface IMainView { //获取手机号 String getMobile(); //获取密码 String getPassword(); //登录成功 void loginSuccess(); //登录失败 void loginError(); }
2.MainActivity

 
 
/** * 登录页 */ public class MainActivity extends AppCompatActivity implements IMainView,View.OnClickListener{ private EditText mobile; private EditText password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout. activity_main); //初始化界面 initViews(); } private void initViews() { //手机号id mobile = (EditText)findViewById(R.id. mobile); //密码id password = (EditText)findViewById(R.id. pwd); //登陆id Button login = (Button) findViewById(R.id. login); //注册id Button reg = (Button) findViewById(R.id. reg); //登录点击事件 login.setOnClickListener( this); //注册点击事件 reg.setOnClickListener( this); } //接口继承 //手机号(调用此方法返回当前手机号) @Override public String getMobile() { return mobile.getText().toString(); } //密码(调用此方法返回当前密码) @Override public String getPassword() { return password.getText().toString(); } //登录成功(调用此方法吐司并跳转到数据展示页面) @Override public void loginSuccess() { Toast. makeText(MainActivity. this, "成功---", Toast. LENGTH_SHORT).show(); startActivity( new Intent(MainActivity. this,GoodsListActivity. class)); } //登录成功(调用此方法吐司失败) @Override public void loginError() { Toast. makeText(MainActivity. this, "失败---请注册", Toast. LENGTH_SHORT).show(); } //点击事件 @Override public void onClick(View v) { switch (v.getId()){ case R.id. login: Presenter presenter = new Presenter(); presenter.loginPresenter( new ModelImpl(), this); break; case R.id. reg: startActivity( new Intent(MainActivity. this,RegActivity. class)); break; } } }
2.5 activity_main(登录页面对应的布局)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.lenovo.monizhoukao2_20180420.view.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="登录"
        android:textSize="25sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp"
        android:background="#999999" />

    <EditText
        android:id="@+id/mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="手机号" />

    <EditText
        android:id="@+id/pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="密码" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="登录" />

        <Button
            android:id="@+id/reg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="注册" />
    </LinearLayout>

</LinearLayout>

3.IRegView

   /**
     * 注册接口
     */
 
 
public interface IRegView { //获取手机号 String getMobile(); //获取密码 String getPassword(); //注册成功 void regSuccess(); //注册失败 void regError(); }
4.RegActivity

   //注册页面

 
 
public class RegActivity extends AppCompatActivity implements IRegView,View.OnClickListener{ private EditText mobile; private EditText password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout. activity_reg); //初始化界面 initViews(); } private void initViews() { //手机号id mobile = (EditText)findViewById(R.id. mobile); //密码id password = (EditText)findViewById(R.id. pwd); //注册id Button reg = (Button) findViewById(R.id. reg); //注册点击事件 reg.setOnClickListener( this); } //点击事件 @Override public void onClick(View v) { switch (v.getId()){ case R.id. reg: Presenter presenter = new Presenter(); presenter.regPresenter( new ModelImpl(), this); break; } } //接口继承 //手机号(调用此方法返回当前手机号) @Override public String getMobile() { return mobile.getText().toString(); } //密码(调用此方法返回当前密码) @Override public String getPassword() { return password.getText().toString(); } //注册成功(调用此方法吐司并跳转到数据展示页面) @Override public void regSuccess() { Toast. makeText(RegActivity. this, "成功---", Toast. LENGTH_SHORT).show(); startActivity( new Intent(RegActivity. this,GoodsListActivity. class)); } //注册失败(调用此方法吐司失败) @Override public void regError() { Toast. makeText(RegActivity. this, "失败---", Toast. LENGTH_SHORT).show(); } }
4.5 activity_reg(注册页面对应的布局)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.lenovo.monizhoukao2_20180420.view.RegActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="注册"
        android:textSize="25sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp"
        android:background="#999999" />

    <EditText
        android:id="@+id/mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="手机号" />

    <EditText
        android:id="@+id/pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="密码" />

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


        <Button
            android:id="@+id/reg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="注册" />
    </LinearLayout>

</LinearLayout>

5.IGoodsListView

   

 
 
/** * Created by lenovo on 2018/4/21. * 商品列表的View接口 */ public interface IGoodsListView { //展示商品列表的方法 void showGoodsList(List<GoosListBean.DataBean> data); }
6.GoodsListActivity

   

/**
 * Created by lenovo on 2018/4/21.
 * 商品列表
 */
 
 
public class GoodsListActivity extends AppCompatActivity implements IGoodsListView,View.OnClickListener { private static final String TAG = "GoodsListActivity"; private ListView listview; private GridView gridView; private boolean flag = true; private ImageView change; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout. activity_goods_list); //初始化界面 initViews(); //请求书 Presenter presenter = new Presenter(); presenter.showGoodsListToView( new ModelImpl(), this); } private void initViews() { change = (ImageView) findViewById(R.id. goodslist_change); listview = (ListView) findViewById(R.id. goodslist_listview); gridView = (GridView) findViewById(R.id. goodslist_gridview); change.setOnClickListener( this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id. goodslist_change: if( flag){ change.setImageResource(R.drawable. lv_icon); gridView.setVisibility(View. VISIBLE); listview.setVisibility(View. GONE); } else{ change.setImageResource(R.drawable. grid_icon); gridView.setVisibility(View. GONE); listview.setVisibility(View. VISIBLE); } flag = ! flag; break; } } //展示商品列表的方法 @Override public void showGoodsList(List<GoosListBean.DataBean> data) { Log. d( TAG, "showGoodsList: "+data); //展示 MyAdapter myAdapter = new MyAdapter(GoodsListActivity. this,data); MyAdapter2 myAdapter2 = new MyAdapter2(GoodsListActivity. this,data); listview.setAdapter(myAdapter); gridView.setAdapter(myAdapter2); } }
6.5 activity_goods_list(商品列表对应的布局)
 
 
 
<? xml version= "1.0" encoding= "utf-8" ?> < LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: app = "http://schemas.android.com/apk/res-auto" xmlns: tools = "http://schemas.android.com/tools" android :layout_width= "match_parent" android :layout_height= "match_parent" android :orientation= "vertical" tools :context= "com.example.lenovo.monizhoukao2_20180420.view.GoodsListActivity"> < FrameLayout android :layout_width= "match_parent" android :layout_height= "wrap_content" android :orientation= "horizontal"> < TextView android :layout_width= "wrap_content" android :layout_height= "wrap_content" android :layout_gravity= "center_horizontal" android :gravity= "center_horizontal" android :text= "商品列表" android :textSize= "25sp" /> < ImageView android :id= "@+id/goodslist_change" android :layout_width= "40dp" android :layout_height= "40dp" android :layout_gravity= "right" android :src= "@drawable/grid_icon" /> </ FrameLayout> < View android :layout_width= "match_parent" android :layout_height= "0.75dp" android :background= "#999999" /> < ListView android : visibility = "visible" android :id= "@+id/goodslist_listview" android :layout_width= "match_parent" android :layout_height= "wrap_content"></ ListView> < GridView android :id= "@+id/goodslist_gridview" android :layout_width= "match_parent" android :layout_height= "wrap_content" android :numColumns= "2" android : visibility = "gone"></ GridView> </ LinearLayout>
五.依赖与需要的配置请求

//联网请求

<uses-permission android:name="android.permission.INTERNET" />
//依赖
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.okhttp3:okhttp:3.3.0'
compile 'com.github.bumptech.glide:glide:3.7.0'

猜你喜欢

转载自blog.csdn.net/Castertonone/article/details/80042009