安卓 原生okhttp使用get与post获取网络数据

网址

https://square.github.io/okhttp/

配置

依赖

在module的build.gradle中:

    implementation 'com.squareup.okhttp3:okhttp:3.14.7'
    implementation 'com.squareup.okio:okio:1.17.5'

AndroidManifest.xml

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

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=".test.TestOKHttpActivity">
    <Button
        android:id="@+id/btn_get_post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get和post" />
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="xx"
        android:textSize="15sp"/>
</LinearLayout>

java代码

public class TestOKHttpActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_get_post;
    private TextView tv_result;
    private OkHttpClient client = new OkHttpClient();
    //设置编码类型
    public static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");
    //get和post请求标识
    private static final int GET = 1;
    private static final int POST = 2;
    //传递消息
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //区分传递的是get还是post消息
            switch (msg.what) {
                case GET://获取数据
                    tv_result.setText((String) msg.obj);
                    break;
                case POST:
                    tv_result.setText((String) msg.obj);
                    break;
            }
        }
    };

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

    private void init() {
        //使用原生的okhttp请求网络数据,get和post
        btn_get_post = findViewById(R.id.btn_get_post);
        tv_result = findViewById(R.id.tv_result);

     
        btn_get_post.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //使用原生的okhttp请求网络数据,get和post
            case R.id.btn_get_post:
                //getDataFromGet();//开启子线程,获取get
                getDataFromPost();//使用post获取数据
                break;
       
        }
    }

    //从子线程中获取网络数据
    private void getDataFromGet() {
        String url = "http://47.108.249.115:8080/LuShuDao0.0.2-1.0-SNAPSHOT/UserInfo/loginUser";
        new Thread() {
            @Override
            public void run() {
                super.run();
                String result = null;
                try {
                    result = get(url);
                    Log.e("Test", result);
                    Message message = Message.obtain();
                    message.what = GET;
                    message.obj = result;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    /*
    okhttp必须在子线程执行
    get请求
    url:请求网址
     */
    private String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }


    //post请求,上传数据,在子线程中执行
    private String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    //从子线程中获取网络数据
    private void getDataFromPost() {
        String url = "http://47.108.249.115:8080/LuShuDao0.0.2-1.0-SNAPSHOT/UserInfo/loginUser";
        new Thread() {
            @Override
            public void run() {
                super.run();
                String result = null;
                try {
                    //json是上传数据
                    result = post(url, "");
                    Log.e("Test", result);
                    Message message = Message.obtain();
                    message.what = POST;
                    message.obj = result;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
}

总结

原生okhttp比较麻烦,使用第三方库去封装使用

上一篇:okhttp android 使用教程


下一篇:面试:OKHttp面试相关问题