使用OKHTTP ,Post请求方式完成登录案例

首先使用OKHTTP 那我们必须导入一下依赖

compile 'com.squareup.okhttp3:okhttp:3.4.2'

接下来一定要切记 配置网络权限

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

MainActivity
使用OKHTTP 操作的具体步骤,详解

package com.example.postlogin;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText mEdName;
    private EditText mEdPwd;
    private Button mBtnLogin;
    private TextView mTv;
    private String path = "http://169.254.53.96:8080/web/LoginServlet";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化资源控件
        initView();
    }

    //获取资源控件id
    private void initView() {
        mEdName = (EditText) findViewById(R.id.ed_name);
        mEdPwd = (EditText) findViewById(R.id.ed_pwd);
        mBtnLogin = (Button) findViewById(R.id.btn_login);
        mTv = (TextView) findViewById(R.id.tv);

        mBtnLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:

                //首先获取用户输入的账号和密码
                String username = mEdName.getText().toString().trim();
                String password = mEdPwd.getText().toString().trim();

                //判断用户输入的账号与密码是否为空
                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
                    Toast.makeText(this, "输入不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

      //////////////////////////// ---------- 使用OKHTTP -- Post请求方式完成登录案列 -------------  ///////////////
                //1.创建okHttpClient对象 以及读取,写入,连接超时
                OkHttpClient client = new OkHttpClient.Builder()
                        //读取超时
                        .readTimeout(10,TimeUnit.SECONDS)
                        //写入超时
                        .writeTimeout(10,TimeUnit.SECONDS)
                        //连接超时
                        .connectTimeout(10,TimeUnit.SECONDS)
                        .build();
                //2.创建FormBody
                FormBody formBody = new FormBody.Builder()
                        .add("qq",username)
                        .add("pwd",password)
                        .build();
                //3.创建request对象
                final Request request = new Request.Builder()
                        //请求方式
                        .post(formBody)
                        //请求接口地址
                        .url(path)
                        .build();
                //4.创建call对象
                Call call = client.newCall(request);

                //5.使用call调用 enqueue完成网络请求
                call.enqueue(new Callback() {
                    //请求失败时调用此方法
                    @Override
                    public void onFailure(Call call, IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "请求网络数据失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    //请求成功时调用该方法
                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                       runOnUiThread(new Runnable() {
                           @Override
                           public void run() {
                               try {
                                   String result = response.body().string();
                                   mTv.setText(result);
                               } catch (IOException e) {
                                   e.printStackTrace();
                               }
                           }
                       });
                    }
                });
                break;
        }
    }

}

布局文件

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

    <EditText
        android:id="@+id/ed_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入账号"/>
    <EditText
        android:id="@+id/ed_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="请输入密码"/>
    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录"/>
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示请求结果"/>

</LinearLayout>

猜你喜欢

转载自blog.csdn.net/LZ0419/article/details/84028083