简单okhttputils

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

权限

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

activity_main.xml

<?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="com.example.day4_okhttputils.MainActivity">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#f00"
        android:textSize="25dp"
        android:gravity="center"
        android:textColor="#fff"
        android:text="标题"/>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_margin="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="请输入手机号"
            android:textSize="20dp"
            android:padding="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/et_tel"
            android:layout_width="match_parent"
            android:hint="请输入手机号"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_margin="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="请输入密    码"
            android:textSize="20dp"
            android:padding="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/et_pwd"
            android:layout_width="match_parent"
            android:hint="请输入密码"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="clip_vertical"
        android:text="注册"

        android:textSize="25dp" />
    <Button
        android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="clip_vertical"
        android:text="注册2"

        android:textSize="25dp" />
    <Button
        android:id="@+id/btn3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="clip_vertical"
        android:text="注册3"

        android:textSize="25dp" />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
MainActivity

package com.example.day4_okhttputils;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
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.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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 etTel;
    /**
     * 请输入密码
     */
    private EditText etPwd;
    /**
     * 注册
     */
    private Button btn;
    /**
     * 注册2
     */
    private Button btn2;
    /**
     * 注册3
     */
    private Button btn3;
    private static String SUBMIT_URL = "https://www.zhaoapi.cn/user/reg?mobile=%s&password=%s";
    private static String URL = "https://www.zhaoapi.cn/user/reg";
    private TextView tv;


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

    }

    private void initView() {
        etTel = (EditText) findViewById(R.id.et_tel);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(this);
        btn2 = (Button) findViewById(R.id.btn2);
        btn2.setOnClickListener(this);
        btn3 = (Button) findViewById(R.id.btn3);
        btn3.setOnClickListener(this);
        tv = (TextView) findViewById(R.id.tv);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn:
                //获取输入的值
                String tel = etTel.getText().toString();
                String pwd = etPwd.getText().toString();
                if (isMobileNO(tel) && checkPwd(pwd)){
                    //submit(tel,pwd);
                    submit2(tel,pwd);
                    //submit3(tel,pwd);
                }else {
                    Toast.makeText(MainActivity.this, "账号密码输入有误!!!", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn2:
                //method1();
                //获取用户输入的用户名和密码
                String n = etTel.getText().toString();
                String p = etPwd.getText().toString();
                //验证用户名或密码是否正确
                if (isMobileNO(n) && !checkPwd(p)) {

                    method2(n, p);
                }
                break;
            case R.id.btn3:
                String s = "?mobile=12354678954&password=123456&";
                String substring = s.substring(0, s.length() - 1);
                Log.e("MainActivity", "substring = " + substring);
                break;
        }
    }
    //传做好的url
    private void method1() {
        OkhttpUtils okhttpUtils = OkhttpUtils.getInstance();
        //获取用户输入的用户名和密码
        String n = etTel.getText().toString();
        String p = etPwd.getText().toString();
        //验证用户名或密码是否正确
        if (isMobileNO(n) && checkPwd(p)) {
            String url = String.format(SUBMIT_URL, n, p);
            okhttpUtils.doGet(url);
        }else {
            Toast.makeText(MainActivity.this, "账号密码输入有误!!!", Toast.LENGTH_SHORT).show();
        }
    }

    private void method2(String name, String pwd) {
        OkhttpUtils okhttpUtils = OkhttpUtils.getInstance();
        Map<String, String> params = new HashMap<>();
        params.put("mobile", name);
        params.put("password", pwd);
        okhttpUtils.doGet2(URL, params, new OnNetListener() {
            @Override
            public void onSuccess(final String str) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(str);
                    }
                });
            }

            @Override
            public void onFailed(Exception e) {

            }
        });
    }
    //post请求
    private void method3(String name, String pwd) {
        OkhttpUtils okhttpUtils = OkhttpUtils.getInstance();
        Map<String, String> params = new HashMap<>();
        params.put("mobile", name);
        params.put("password", pwd);
        okhttpUtils.doPost(URL,params);
    }

    //注册
    private void submit(String name,String pwd){
        //创建OkHttpClient
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建requet对象
        String url=String.format(SUBMIT_URL,name,pwd);
        Request request = new Request.Builder().url(url).build();
        //进行请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(string);
                    }
                });
            }
        });

    }
    //同步请求
    private void submit2(String name,String pwd){
        final OkHttpClient okHttpClient = new OkHttpClient();
        String url=String.format(SUBMIT_URL,name,pwd);
        final Request request = new Request.Builder().url(url).build();
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    String string = response.body().string();
                    Log.e("MainActivity", "string = " + string);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //post请求
    private void submit3(String name, String pwd) {
        //创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建Request
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("mobile",name);
        builder.add("password",pwd);
        FormBody build = builder.build();
        Request request = new Request.Builder().url("https://www.zhaoapi.cn/user/reg").post(build).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                new Thread(){
                    @Override
                    public void run() {
                        tv.setText(string);
                    }
                }.start();
            }
        });


    }



    // 验证手机号是否为正确手机号
    public static boolean isMobileNO(String mobiles) {

        Pattern p = Pattern
                .compile("^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$");

        Matcher m = p.matcher(mobiles);

        return m.matches();
    }

    //验证手机格式

    public static boolean isMobileNO1(String mobiles) {
        /*
        移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
        联通:130、131、132、152、155、156、185、186
        电信:133、153、180、189、(1349卫通)/^0?1[3|4|5|7|8][0-9]\d{8}$/
        总结起来就是第一位必定为1,第二位必定为3或5或8或7(电信运营商),其他位置的可以为0-9
        */
        String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);
    }
     // 验证邮箱
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }
    /**
     * 验证密码是否为空
     *
     * @param pwd
     * @return
     */
    private boolean checkPwd(String pwd) {
        //pwd.length()>=6 && pwd.length()<=20 &&
        if ( !TextUtils.isEmpty(pwd)){
            return true;
        }else {
            return false;
        }
    }

}
OkhttpUtils
package com.example.day4_okhttputils;

import android.util.Log;

import java.io.IOException;
import java.util.Map;

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

/**
 * Created by asus on 2018/4/13.
 */

public class OkhttpUtils {
    //private static OkhttpUtils okhttpUtils =new OkhttpUtils();//饿汉式
    private static OkhttpUtils okhttpUtils;
    private final OkHttpClient okHttpClient;

    private OkhttpUtils(){
        okHttpClient = new OkHttpClient();
    }
    //懒汉式 synchronizedt同步
    public synchronized static OkhttpUtils getInstance(){
        if (okhttpUtils==null){
            okhttpUtils=new OkhttpUtils();

        }
        return okhttpUtils;
    }


    //饿汉式
//    public static OkhttpUtils getInstance(){
//        return okhttpUtils;
//    }
    //传做好的url
    public void doGet(String url) {
        //创建Requet对象
        Request request = new Request.Builder().url(url).build();
        //进行请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("MainActivity", "string = " + string);
            }
        });
    }

    //传url和参数回传
    public void doGet2(String url, Map<String, String> params, final OnNetListener onNetListener) {
        //判断params是否为空
        if (params!=null){
            StringBuilder sb = new StringBuilder();
            sb.append("?");
            for (Map.Entry<String,String> entry:params.entrySet()) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }
            //
            String s = sb.toString();
            String strparam = s.substring(0, s.length() - 1);
            url+= strparam;

        }
        Request request = new Request.Builder().url(url).build();
        //发送请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onNetListener.onFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                onNetListener.onSuccess(string);
            }
        });
    }

    public void doPost(String url, Map<String, String> params) {
        if (params != null) {
            //创建FormBody用于封装参数
            FormBody.Builder fBuilder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                fBuilder.add(entry.getKey(), entry.getValue());
            }
            FormBody formBody = fBuilder.build();
            Request.Builder builder = new Request.Builder();
            builder.url(url);
            builder.post(formBody);
            //创建Request
            Request request = builder.build();

            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String string = response.body().string();
                    Log.e("MainActivity", "string = " + string);
                }
            });
        }

    }
}
OnNetListener
package com.example.day4_okhttputils;

/**
 * Created by asus on 2018/4/13.
 */

public interface OnNetListener {
    void onSuccess(String str);

    void onFailed(Exception e);
}


阅读更多
上一篇二维码
下一篇加减
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭