1. 程式人生 > >OkHttpClient 進行網路請求

OkHttpClient 進行網路請求

package com.example.mvpdemotwo.modle;

import android.util.Log;
import android.widget.Toast;

import com.example.mvpdemotwo.MainActivity;

import java.io.IOException;

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

/**
 * Created by hasee on 2018/1/30.
 */

public class LoginModle {

    //model層的login方法,對應presenter中的login方法
    public void login(String mobile, String password) {

        //如果mvc的話,直接在這個位置去聯網請求
        //如果是mvp的話,我們需要把聯網的操作放到modle中

        //構建一個OkHttpClient物件
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .build();

        //通過表單的形式,構建一個RequestBody,通過新增key-value的形式,上傳引數
        RequestBody requestBody = new FormBody.Builder()
                .add("source","android")
                .add("mobile",mobile)
                .add("password",password)
                .build();

        //通過我們構造的requestBody物件,去構造一個Request
        Request request = new Request.Builder()
                .url("https://www.zhaoapi.cn/user/login")
                .post(requestBody)
                .build();

        //使用okHttpClient物件執行newCall,傳入一個Request,去構造一個call請求
        Call call = okHttpClient.newCall(request);

        //通過這個call請求去非同步的請求登入介面
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("tag","============================onFailure");
                //okhttp的回撥是在子執行緒的
                //切到主執行緒,更新UI
                 runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                         //登入失敗
                         Toast.makeText(MainActivity.this, "登入失敗", Toast.LENGTH_LONG).show();
 
                     }
                 });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                 runOnUiThread(new Runnable() {
                     @Override
                   public void run() {
                         //登入成功
                         Toast.makeText(MainActivity.this, "登入成功", Toast.LENGTH_LONG).show();
                     }
                 });
                Log.e("tag","============================onResponse");
            }
        });
    }
}