仿登录界面,Android调用服务器后端api,提交GET/POST参数,返回json格式数据

(这段话可以省略不看)记得从学校出来实习,入职第一家公司时,第一次听到Android调用api接口,获取后台的数据。感觉一脸懵逼,因为在学校做的一些安卓项目基本都是原生的app知识,基础控件的使用,甚至需要网络服务的项目都是少的可怜。回到上个问题,在网上找了一下资料,整理了代码。

不扯话题了,看下面完整代码。

    第一(简单布局图):

                        

布局文件:activity_login.xml

<?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"
    android:orientation="vertical"
    tools:context="com.example.think.textone_login.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试登录"
        android:gravity="center"
        android:textSize="28dp"
        />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="15dp">
        <EditText
            android:id="@+id/et_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="用户名"
            />
        <EditText
            android:id="@+id/et_psd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="密码"
            />
        <Button
            android:id="@+id/bt_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="登录"
            />
    </LinearLayout>

</LinearLayout>
字符转换类 NetUtils.java :
public class NetUtils {
    public static byte[] readBytes(InputStream is){
        try {
            byte[] buffer = new byte[1024];
            int len = -1 ;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while((len = is.read(buffer)) != -1){
                baos.write(buffer, 0, len);
            }
            baos.close();
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }
    public static String readString(InputStream is){

        return new String(readBytes(is));
    }

}

LoginActivity.java:

  

public class LoginActivity extends AppCompatActivity {
    private EditText et_username, et_psd;
    private Button bt_login;
    private String resultCode,resultMsg;
    String account, pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //隐藏标题
        getSupportActionBar().hide();
        init();
    }

    private void init() {
        et_username = findViewById(R.id.et_username);
        et_psd = findViewById(R.id.et_psd);
        bt_login = findViewById(R.id.bt_login);
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取相应用户名和密码
                account = et_username.getText().toString();
                pwd = et_psd.getText().toString();
                if (account.equals("") || pwd.equals("")) {
                    Toast.makeText(getApplicationContext(), "用户名或密码为空", Toast.LENGTH_SHORT).show();
                }
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int num = init_api(account, pwd);
                        if (resultCode.equals("0")) {
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        } else {
                            Toast.makeText(getApplicationContext(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
                        }
                    }

                });
                thread.start();
            }
        });
    }


    private int init_api(String account, String pwd) {
        String urlPath = "http://xxxxxxxx/api/v1.index/login";
        URL url;
        int id = 0;
        try {
            url = new URL(urlPath);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("account", account);
            jsonObject.put("pwd", pwd);
            //参数put到json
            String content = String.valueOf(jsonObject);
            //开启连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");//提交方式
            conn.setRequestProperty("Content-Type", "application/json");


            //写输出流,将要转的参数写入流
            OutputStream os = conn.getOutputStream();
            os.write(content.getBytes());
            os.close();
            int code = conn.getResponseCode();
            if (code == 200) {
                //读取返回的json
                InputStream inputStream = conn.getInputStream();
                //调用NetUtils() 将流转成String类型
                String json = NetUtils.readString(inputStream);
                System.out.println("adad" + json);
                JSONObject jsonObject1 = new JSONObject(json);
                 resultCode = jsonObject1.getString("resultCode");
                 resultMsg = jsonObject1.getString("resultMsg");
                System.out.println("json返回状态码====" + resultCode);
                System.out.println("json返回消息======" + resultMsg);
            } else {
                Toast.makeText(getApplicationContext(), "数据提交失败", Toast.LENGTH_SHORT).show();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return id;
    }
}

最后根据json返回的状态码(resultCode),确认跳转状态,如果为0,跳转MainActivity,显示一句话。

成功登录页面:MainActivity:

json返回数据:如图

最后由于时间仓促和自己的水平能力有限,很多东西写的不好,欢迎大家评论指点。以后Android开发遇到的坑,尽量在csdn上面分享,同时也会学习更多编程的知识,使得自己成长起来。

猜你喜欢

转载自blog.csdn.net/qq_36771930/article/details/87890306