• Android请求获取Java后端数据,登录界面例子


    最近做了个Android请求获取Java后端数据的例子,简单实现了一下。


    先上个登录界面图:   

    登录界面使用 http://blog.csdn.net/u012964281/article/details/40625967  ,有点小改动。

    源代码下载:Android请求获取Java后端数据,登录界面例子

    主要实现:

    java后端的代码 + Android的代码

    1、java后端

    (1)、先创个User类

    import net.sf.json.JSONObject;
    public class User {
    	private long userid;
    	private String account;
        private String username;
        private String passwd;
        public User(long userid, String account, String username, String passwd) {
            this.userid = userid;
            this.account = account;
            this.username = username;
            this.passwd = passwd;
        }
        public static User json2novel (JSONObject json) {
            try {
                return new User(json.getLong("userid"),
                        json.getString("account"),
                        json.getString("username"),
                        json.getString("passwd")
                );
            }catch (Exception ex) {
            	ex.printStackTrace();
            }
            return null;
        }
        public long getUserid() {
    		return userid;
    	}
    	public void setUserid(long userid) {
    		this.userid = userid;
    	}
    	public String getAccount() {
    		return account;
    	}
    	public void setAccount(String account) {
    		this.account = account;
    	}
    	public String getUsername() {
    		return username;
    	}
    	public void setUsername(String username) {
    		this.username = username;
    	}
    	public String getPasswd() {
    		return passwd;
    	}
    	public void setPasswd(String passwd) {
    		this.passwd = passwd;
    	}    
    }

    (2)、建个LoginServlet(public class LoginServlet extends HttpServlet)

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import net.sf.json.JSONObject;
    public class LoginServlet extends HttpServlet{
    	@Override
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doPost(request, response);
    	}
    	@Override
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");
    		response.setContentType("text/html;charset=UTF-8");
    		JSONObject json = new JSONObject();
    		List<User> list = new ArrayList<>();
    		User user = new User(1,"sa","sa","123");
    		list.add(user);
    		json.put("data", list);
    		PrintWriter out = response.getWriter();
    		out.write(json.toString());//返回json数据
    	}
    }

    (3)、建个跨域过滤器CorsFilter(public class CorsFilter implements Filter)

    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletResponse;
    public class CorsFilter implements Filter {
    	@Override
    	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    		HttpServletResponse res = (HttpServletResponse) response;
    		res.setContentType("text/html;charset=UTF-8");
    		res.setHeader("Access-Control-Allow-Origin", "*");//"*"所有域名可访问
    		res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    		res.setHeader("Access-Control-Max-Age", "0");
    		res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
    		res.setHeader("Access-Control-Allow-Credentials", "true");
    		res.setHeader("XDomainRequestAllowed", "1");
    		chain.doFilter(request, response);
    	}
    	@Override
    	public void init(FilterConfig config) throws ServletException {
    	}
    	@Override
    	public void destroy() {
    	}
    }

    (4)、配置一下web.xml

    	<servlet>
    		<servlet-name>LoginServlet</servlet-name>
    		<servlet-class>com.gxzj.login.LoginServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>LoginServlet</servlet-name>
    		<url-pattern>/LoginServlet</url-pattern>
    	</servlet-mapping>
      
        <!-- 设置跨域访问过滤器 -->
    	<filter>  
    		<filter-name>cors</filter-name>  
    		<filter-class>com.gxzj.login.CorsFilter</filter-class>  
    	</filter>  
    	<filter-mapping>  
    		<filter-name>cors</filter-name>  
    		<url-pattern>/*</url-pattern>  
    	</filter-mapping>

    2、Android代码

    (1)、写个登录界面xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#e7e7e7"
        android:orientation="vertical"
        android:padding="10dp">
    
        <ImageView
            android:layout_width="132dp"
            android:layout_height="132dp"
            android:layout_gravity="center"
            android:layout_marginTop="45dp"
            android:src="@drawable/icon_avatar_login" />
    
        <LinearLayout
            android:id="@+id/login_linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="8dp"
            android:orientation="vertical">
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:background="@drawable/login_input"
                android:orientation="vertical">
    
                <LinearLayout
                    android:id="@+id/userId_LinearLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="45dp"
                    android:gravity="right"
                    android:orientation="horizontal">
    
                    <!-- android:ems="10"表示EditText内最多只显示10个字符,超出不显示 -->
                    <!-- android:singleLine="true"表示不能全部显示时,后面用“…”来表示 -->
                    <EditText
                        android:id="@+id/login_edtId"
                        android:layout_width="0dp"
                        android:layout_height="44dp"
                        android:layout_weight="1"
                        android:background="@null"
                        android:ems="10"
                        android:hint="用户名"
                        android:paddingLeft="15dp"
                        android:paddingRight="15dp"
                        android:singleLine="true"
                        android:textColorHint="#999999"
                        android:textSize="18sp">
                        <requestFocus />
                    </EditText>
    
                    <ImageView
                        android:id="@+id/login_more_user"
                        android:layout_width="wrap_content"
                        android:layout_height="44dp"
                        android:layout_marginRight="15dp"
                        android:layout_marginTop="5dp"
                        android:src="@drawable/login_more_up" />
                </LinearLayout>
    
                <!-- 横线  -->
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="#CACDD1" />
    
                <EditText
                    android:id="@+id/login_edtPwd"
                    android:layout_width="match_parent"
                    android:layout_height="44dp"
                    android:layout_marginTop="10dp"
                    android:background="@null"
                    android:hint="密码"
                    android:inputType="textPassword"
                    android:paddingLeft="15dp"
                    android:paddingRight="0dp"
                    android:singleLine="true"
                    android:textColorHint="#999999"
                    android:textSize="18sp" />
            </LinearLayout>
    
            <Button
                android:id="@+id/btn_login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:background="@drawable/btn_bg"
                android:text="登 录"
                android:textColor="#fff"
                android:textSize="22sp" />
    
        </LinearLayout>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/login_txtForgotPwd"
                android:layout_width="0dp"
                android:layout_weight="1.0"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:layout_marginLeft="22dp"
                android:text="忘记密码?"
                android:textColor="#0079FF"
                android:textSize="18sp"/>
    
            <TextView
                android:id="@+id/btn_register"
                android:layout_width="0dp"
                android:layout_weight="1.0"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:layout_marginRight="22dp"
                android:text="注册"
                android:textColor="#0079FF"
                android:textSize="18sp"
                android:layout_gravity="end"
                android:textAlignment="textEnd"/>
    
        </LinearLayout>
    
    </LinearLayout>

    (2)、再写点LoginActivity代码

    请求网络数据需要权限,在manifest添加权限:

    <uses-permission android:name="android.permission.INTERNET" />

    这里使用了 AsyncHttpClient 来请求 java后端 的数据

    要在build里添加:

    compile 'com.loopj.android:android-async-http:1.4.9'
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    import com.loopj.android.http.AsyncHttpClient;
    import com.loopj.android.http.AsyncHttpResponseHandler;
    import org.json.JSONArray;
    import org.json.JSONObject;
    import java.util.ArrayList;
    import java.util.List;
    import cz.msebera.android.httpclient.Header;
    public class LoginActivity extends AppCompatActivity {
        AsyncHttpClient client;//异步加载
        List<User> ls_user = null;
        Button btn_login;
        EditText login_edtId,login_edtPwd;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            client = new AsyncHttpClient();//实例化AsyncHttpClient
            btn_login = (Button) findViewById(R.id.btn_login);
            login_edtId = (EditText) findViewById(R.id.login_edtId);
            login_edtPwd = (EditText) findViewById(R.id.login_edtPwd);
            btn_login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String account = login_edtId.getText().toString().trim();
                    String passwd = login_edtPwd.getText().toString().trim();
                    if(account.equals("")){
                        Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                    }else if(passwd.equals("")){
                        Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    }else{
                        //这里的IP(192.168.43.234:8080)要换成你自己的IP !!!
                        String url = "http://192.168.3.126:8080/Cors/LoginServlet?account=" + account + "&passwd=" + passwd;
                        ls_user = new ArrayList<>();//初始化
                        client.get(url, new AsyncHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                                try {
                                    JSONObject jsonObject = new JSONObject(new String(responseBody));
                                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                                    for (int i=0; i<jsonArray.length(); ++i) {
                                        User user = User.json2novel(jsonArray.getJSONObject(i));
                                        if (user != null) {
                                            ls_user.add(user);
                                        }
                                    }
                                    if(ls_user.size() == 1){
                                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                        startActivity(intent);
                                    }else{
                                        Toast.makeText(LoginActivity.this, "用户名或密码", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Toast.makeText(LoginActivity.this, "登陆失败!", Toast.LENGTH_SHORT).show();
                                }
                            }
                            @Override
                            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                                Toast.makeText(LoginActivity.this, "登陆错误!", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
        }
    }

    (3)、MainActivity就直接创建一个空Activity

    (4)、建个User类

    import org.json.JSONException;
    import org.json.JSONObject;
    public class User {
        private long userid;
        private String account;
        private String username;
        private String passwd;
        public User(long userid, String account, String username, String passwd) {
            this.userid = userid;
            this.account = account;
            this.username = username;
            this.passwd = passwd;
        }
        public static User json2novel (JSONObject json) {
            try {
                return new User(json.getLong("userid"),
                        json.getString("account"),
                        json.getString("username"),
                        json.getString("passwd")
                );
            }catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    }


    以前觉得一个项目访问另外一个项目资源是需要跨域的,是没弄懂跨域的概念,跨域:

    什么是跨域?

    关于跨域,以及跨域的几种方式

    代码大概就这个样子了,菜鸟一个,请多多谅解,源码下载:

    Android请求获取Java后端数据,登录界面例子



     

  • 相关阅读:
    手头上的几本关于实现程序设计语言的书
    Ubuntu 16.04 搭建KVM环境
    调用RESTful GET方法
    Ubuntu 16.04 安装Docker
    Ubuntu 16.04安装Java 8
    SecureCRT 多个会话显示在同一窗口
    Ubuntu 16.04 安装Maven3.3.9
    Python标准类型的分类
    Ubuntu 16.04 更改apt源
    LVM术语及相互关系
  • 原文地址:https://www.cnblogs.com/qq1995/p/10359021.html
Copyright © 2020-2023  润新知