【达内课程】网络通信之HTTP协议(4)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010356768/article/details/81541590

这里写图片描述

无状态:服务端不保存客户端状态

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

我们上一节的登录并没有保存登录的状态,需要保存登录状态,需要给服务器传会JSESSIONID,用一个栗子做一下
我们需要一个这样的布局
这里写图片描述
activity_main

<?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.xx.myapplication.MainActivity">

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

        <TextView
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:text="用户名"/>

        <EditText
            android:id="@+id/et_number"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

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

        <TextView
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:text="密码"/>

        <EditText
            android:id="@+id/et_password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

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

        <TextView
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:text="验证码"/>

        <EditText
            android:id="@+id/et_captcha"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

        <ImageView
            android:id="@+id/img_captcha"
            android:layout_width="100dp"
            android:layout_height="50dp"
            />
    </LinearLayout>

    <Button
        android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="确定" />

</LinearLayout>

MainActivity

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_add;
    private EditText et_number;
    private EditText et_password;
    private EditText et_captcha;
    private ImageView img_captcha;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case LOGIN_SUCCESS:
                    Toast.makeText(MainActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                    //界面跳转到CardListActivity
                    Intent intent = new Intent(MainActivity.this,ShopListActivity.class);
                    startActivity(intent);
                    break;
                case LOGIN_FAIL:
                    Toast.makeText(MainActivity.this,"登录失败:"+msg.obj,Toast.LENGTH_SHORT).show();
                    break;
                case HANDLER_LOAD_IMAGE_SUCCESS:
                    if(bitmap != null){
                        img_captcha.setImageBitmap(bitmap);
                    }else {
                        img_captcha.setImageResource(R.mipmap.ic_launcher);
                    }
                    break;
            }
        }
    };

    public static final int LOGIN_SUCCESS = 1;
    public static final int LOGIN_FAIL = 2;
    public static final int HANDLER_LOAD_IMAGE_SUCCESS = 3;
    private Bitmap bitmap;
    private String JSESSIONID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setViews();
        //发送http请求,获取验证码图片
        new Thread(){
            @Override
            public void run() {
                try {
                    loadImage();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    private void loadImage() throws IOException{
        URL url = new URL("http://域名/site/captcha.html?refresh=1&format=raw&user_agent=szyapp/android");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();
        //把输入流解析为Bitmap对象
        bitmap = BitmapFactory.decodeStream(is);
        //获取响应数据包中的Set-Cookie中的JSESSIONID
        String val = conn.getHeaderField("Set-Cookie");
        Log.i("JSESSIONID",val);
       JSESSIONID = val.split(";")[0];
        //把bitmap显示到Imageview,发消息给handler
        handler.sendEmptyMessage(HANDLER_LOAD_IMAGE_SUCCESS);
    }


    private void setViews() {
        et_number = findViewById(R.id.et_number);
        et_password = findViewById(R.id.et_password);
        et_captcha = findViewById(R.id.et_captcha);
        img_captcha = findViewById(R.id.img_captcha);

        btn_add = findViewById(R.id.btn_add);
        btn_add.setOnClickListener(this);

        img_captcha.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_add:
                new Thread(){
                    @Override
                    public void run() {
                        try {
                            login();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
            case R.id.img_captcha:
                new Thread(){
                    @Override
                    public void run() {
                        try {
                            loadImage();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
        }
    }

    private void login() throws IOException, JSONException {
        //1、URL
        URL url = new URL("http://域名/site/login");
        //2、HttpURLConnection
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //3、setRequestMethod  setRequestProperty()
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        conn.setRequestProperty("Cookie",JSESSIONID);
        //4、doOutPut
        conn.setDoInput(true);
        OutputStream os = conn.getOutputStream();
        //5、构建参数
        String user_name = et_number.getText().toString();
        String password = et_password.getText().toString();
        String captcha = et_captcha.getText().toString();
        String param = "user_agent=szyapp/android&user_name="+user_name+"&password="+password+"&verifyCode="+captcha;
        os.write(param.getBytes("utf-8"));
        os.flush();
        //6、inputStream
        InputStream is = conn.getInputStream();
        //7、is转换成String
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = "";
        while ((line = reader.readLine())!=null){
            sb.append(line);
        }

        String json = sb.toString();
        //7、解析json
        JSONObject obj = new JSONObject(json);
        String res = obj.getString("code");
        //8、发消息给Handler
        if(res.equals("0")){
            //成功
            handler.sendEmptyMessage(LOGIN_SUCCESS);
        }else{
            //失败
            Message msg = new Message();
            msg.what = LOGIN_FAIL;
            msg.obj = obj.getString("message");
            handler.sendMessage(msg);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u010356768/article/details/81541590