okhttp异步get和post请求,实现读取获取、增加http文件数据

Okhttp类,封装方法

java 复制代码
package com.example.httptest;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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;

public class Okhttp {
    private static final String TAG = "Okhttp";
    private Context context;//上下文环境
    private static final String DB_NAME = "Account.db";//数据库名
    private static final int DB_VERSION = 1;//数据库版本号
    private static final String TABLE_NAME = "User";//表名
    private Context mContext;
    // 列名称
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_PASSWORD = "password";
    private static final String COLUMN_MONEY = "money";
    private DBHelper mDBHelper;
    private SQLiteDatabase mSQLiteDatabase;

    private final OkHttpClient okHttpClient = new OkHttpClient();

    Account mAccount = new Account();

    //异步get请求 调用enqueue()方法,传入回调函数 查所有用户数据
    public void doGetAsync() {
        Request request = new Request.Builder().url("http://192.168.1.3:3000/Account/AddAccount").build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String string = response.body().string();
                /*Map<String, String> map = new HashMap<String, String>();
                map.put("username","username");
                map.put("password","password");
                map.put("money","money");
                map.put("id","id");
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(map);
                JSONObject jsonObject = JSONObject.fromObject(map);*/
                // JSONArray jsonArray = new JSONArray(string);

                // JSONArray object = new JsonParse().parse(string).getAsJsonArray();

                JsonArray jsonArray = new JsonParser().parse(string).getAsJsonArray();


                //  Gson gson = new Gson();
//Account account = new Account(1,"xiaoming","123",0.0);

                //String j = gson.toJson(string);
                //   Account acc = gson.fromJson(string, Account.class);
//Log.e(TAG, String.valueOf(acc));
                //int v1 = acc.getId();
                //Log.e(TAG, String.valueOf(v1));


            }
        });
    }

    public void addAccountSQlite(JSONObject jsonObject) throws JSONException {
        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("username", "1");
        //SQLiteDatabase db = helper.getReadableDatabase();
        // String sql = "insert into User values(" + id + ',' + name + ',' + pwd + ',' + 0.0 + ")";

        Log.e(TAG, jsonObject.getString("key1"));
    }


    public void doGetAccount() {
        Request request = new Request.Builder().url("http://192.168.1.3:3000/Account/GetAccount?username=XiaoMing").build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "失败");
            }

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

            }
        });
    }

    //异步post请求  调用enqueue()方法,传入回调函数  新增用户
    public void doPostAsync() {
        RequestBody body = new FormBody.Builder()
                // FormBody formBody = new FormBody.Builder()
                .add("username", "xiao9")
                .add("password", "9")
                .add("money", "9")
                .add("id", "23")
                .build();
        Request request = new Request.Builder().url("http://192.168.1.3:3000/Account/AddAccount")
                .post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.e(TAG, "成功");
                    Log.e(TAG, "doPostAsync: " + response.body().string());
                }
            }
        });
    }
}

activity类

java 复制代码
<?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"
    android:gravity="center"
    android:layout_margin="10dp">

    <Button
        android:id="@+id/GetAllAccountGetbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GetAllAccount Get接口"
        android:textSize="25dp" />

    <Button
        android:id="@+id/GetAccountGetbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GetAccount Get接口"
        android:textSize="25dp"
        android:layout_marginTop="30dp"/>

    <Button
        android:id="@+id/AddAccountPostbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="AddAccount Post接口"
        android:textSize="25dp"
        android:layout_marginTop="30dp"/>
    
</LinearLayout>

MainActivity

java 复制代码
package com.example.httptest;

import static android.content.ContentValues.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.accounts.Account;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayList<Account> mAccounts = new ArrayList<>();
    private Button mGetAllAccountGetbutton;
    private Button mGetAccountGetbutton;
    private Button mAddAccountPostbutton;
    private Okhttp mOkhttp = new Okhttp();


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

        mGetAllAccountGetbutton = findViewById(R.id.GetAllAccountGetbutton);
        mGetAllAccountGetbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOkhttp.doGetAsync();

            }
        });
        mAddAccountPostbutton = findViewById(R.id.AddAccountPostbutton);
        mAddAccountPostbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOkhttp.doPostAsync();
            }
        });

        mGetAccountGetbutton = findViewById(R.id.GetAccountGetbutton);
        mGetAccountGetbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOkhttp.doGetAccount();
            }
        });

    }
}
相关推荐
风和先行13 分钟前
adb 命令查看设备存储占用情况
android·adb
AaVictory.1 小时前
Android 开发 Java中 list实现 按照时间格式 yyyy-MM-dd HH:mm 顺序
android·java·list
似霰2 小时前
安卓智能指针sp、wp、RefBase浅析
android·c++·binder
大风起兮云飞扬丶2 小时前
Android——网络请求
android
干一行,爱一行2 小时前
android camera data -> surface 显示
android
断墨先生2 小时前
uniapp—android原生插件开发(3Android真机调试)
android·uni-app
无极程序员4 小时前
PHP常量
android·ide·android studio
萌面小侠Plus5 小时前
Android笔记(三十三):封装设备性能级别判断工具——低端机还是高端机
android·性能优化·kotlin·工具类·低端机
慢慢成长的码农5 小时前
Android Profiler 内存分析
android
大风起兮云飞扬丶5 小时前
Android——多线程、线程通信、handler机制
android