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

    }
}
相关推荐
Dingdangr3 小时前
Android中的Intent的作用
android
技术无疆3 小时前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
GEEKVIP3 小时前
Android 恢复挑战和解决方案:如何从 Android 设备恢复删除的文件
android·笔记·安全·macos·智能手机·电脑·笔记本电脑
Jouzzy10 小时前
【Android安全】Ubuntu 16.04安装GDB和GEF
android·ubuntu·gdb
极客先躯10 小时前
java和kotlin 可以同时运行吗
android·java·开发语言·kotlin·同时运行
茜茜西西CeCe13 小时前
移动技术开发:登录注册界面
java·gitee·gradle·android studio·安卓·移动技术开发·原生安卓开发
Good_tea_h13 小时前
Android中的单例模式
android·单例模式
陶甜也17 小时前
前后端分离,使用MOCK进行数据模拟开发,让前端攻城师独立于后端进行开发
前端·okhttp
计算机源码社18 小时前
分享一个基于微信小程序的居家养老服务小程序 养老服务预约安卓app uniapp(源码、调试、LW、开题、PPT)
android·微信小程序·uni-app·毕业设计项目·毕业设计源码·计算机课程设计·计算机毕业设计开题
丶白泽18 小时前
重修设计模式-结构型-门面模式
android