展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

okhttp基础使用(一)

  • 新建一个安卓项目

  • build.gradle (:app)中添加如下依赖

android {
    android.buildFeatures.viewBinding = true
}

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:3.14.+'
}
  • 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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试请求"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>
  • 修改MainActivity
package com.example.okhttp;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.example.okhttp.databinding.ActivityMainBinding;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;

    OkHttpClient okHttpclient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
//        setContentView(R.layout.activity_main);

        okHttpclient = new OkHttpClient.Builder().build();

        binding.btn1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                // 执行get请求
                testGet();
            }
        });
    }

    // 发送get请求
    private void testGet(){
        Request request = new Request.Builder().url("http://127.0.0.1:4523/m1/4635458-4285948-default/pet/1").build();

        // 同步请求
        new Thread(new Runnable(){
            @Override
            public void run(){
                try {
                    Response response = okHttpclient.newCall(request).execute();
                    String result = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 响应内容显示到页面
                            binding.textView.setText(result);
                        }
                    });
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
  • AndroidManifest.xml中进行网络配置
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  • src > main > res > xml中新建network_security_config.xml文件

  • 将配置文件加入AndroidManifest.xml

<application
        android:networkSecurityConfig="@xml/network_security_config"
>
  • 启动虚拟环境,启动app,点击按钮测试

  • 发送异步请求

    // 发送get请求
    private void testGet() {

        FormBody formBody = new FormBody.Builder().add("test", "这是一个测试的参数").build();
        Request request = new Request.Builder().url("http://192.168.0.109:6666/fc/test").post(formBody).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 result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 显示到页面
                        binding.textView.setText(result);
                    }
                });
            }
        });
    }
  • 异步请求方式2
    // 发送get请求
    private void testGet() {

        RequestBody requestBody = RequestBody.create(MediaType.
                parse("application/json; charset=utf-8"),"\"requestBody数据实体\"");
        Request request = new Request.Builder().url("http://192.168.0.109:6666/fc/test2").post(requestBody).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 result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 显示到页面
                        binding.textView.setText(result);
                    }
                });
            }
        });
    }
posted @ 2024-08-05 14:32  DogLeftover  阅读(21)  评论(0编辑  收藏  举报