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();
            }
        });

    }
}
相关推荐
Cao_Shixin攻城狮2 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
呼啦啦呼啦啦啦啦啦啦5 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
idjl7 小时前
Mysql测试题
android·adb
游戏开发爱好者89 小时前
iOS App 电池消耗管理与优化 提升用户体验的完整指南
android·ios·小程序·https·uni-app·iphone·webview
人生游戏牛马NPC1号10 小时前
学习 Flutter (四):玩安卓项目实战 - 中
android·学习·flutter
星辰也为你祝福h11 小时前
Android原生Dialog
android
梁同学与Android12 小时前
Android ---【CPU优化】需要优化的原因及优化的地方
android
Misha韩13 小时前
React Native 基础tabBar和自定义tabBar - bottom-tabs
android·react native
iHero13 小时前
【Nextcloud】在 Ubuntu 22.04.3 LTS 上的 Nextcloud Hub 10 (31.0.2) 后台任务cron 的优化
android·linux·ubuntu·nextcloud
imknown14 小时前
将一个 现有 iOS Xcode 项目, 快速改造为 可以用 Android Studio 运行和调试 的项目
android studio