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

这篇具有很好参考价值的文章主要介绍了okhttp异步get和post请求,实现读取获取、增加http文件数据。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Okhttp类,封装方法

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类

<?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文章来源地址https://www.toymoban.com/news/detail-627256.html

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

    }
}

到了这里,关于okhttp异步get和post请求,实现读取获取、增加http文件数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用Python接口自动化测试post请求和get请求,获取请求返回值

    目录 引言 请求接口为Post时,传参方法  获取接口请求响应数据 我们在做python接口自动化测试时,接口的请求方法有get,post等;get和post请求传参,和获取接口响应数据的方法; 我们在使用python中requests库做接口测试时,在做post接口测试传参的时候,需要传入请求体,我们把

    2024年02月02日
    浏览(41)
  • php实战案例记录(15)获取GET和POST请求参数

    在PHP中,可以使用 $_GET 和 $_POST 超全局变量来获取GET和POST请求参数。 获取GET请求参数: 要获取GET请求参数,可以使用 $_GET 超全局变量。它是一个关联数组,其中键是参数的名称,值是参数的值。例如,如果URL是 http://example.com/page.php?name=Johnage=25 ,可以使用以下代码获取参数

    2024年02月07日
    浏览(37)
  • thinkphp6 入门(3)--获取GET、POST请求的参数值

    一、 Request 对象 thinkphp提供了 Request 对象,其可以 支持对全局输入变量的检测、获取和安全过滤 支持获取包括 $_GET 、 $_POST 、 $_REQUEST 、 $_SERVER 、 $_SESSION 、 $_COOKIE 、 $_ENV 等系统变量,以及文件上传信息 具体参考:https://www.kancloud.cn/manual/thinkphp6_0/1037519 二、可以通过Reque

    2024年02月11日
    浏览(33)
  • node.js中获取前端传递的get、post请求参数

    req.query:get请求; req.body:post请求; (1) get请求:  (2) post请求:      第一步:下载body-parser模块      第二步:引入body-parser模块      第三步:使用body-parser模块      第四步:使用body-parser模块的参数json方法      第五步:获取参数

    2024年02月13日
    浏览(32)
  • 使用Flask.Request的方法和属性,获取get和post请求参数(二)

    在Python发送Post、Get等请求时,我们使用到requests库。Flask中有一个request库,有其特有的一些方法和属性,注意跟requests不是同一个。 用于服务端获取客户端请求数据。注意:是未经任何处理的原始数据而不管内容类型,如果数据时json的,则取得是json字符串,排序和请求参数

    2024年02月13日
    浏览(37)
  • 谷歌浏览器通过network模拟HTTP中的GET/POST请求获取response

    1、F12打开network选中需要模拟的方法Copy-Copy as fetch 2、通过AI帮你进行转换一下调用格式  原代码 通过文心一言转换(有条件的可以用ChatGPT) 问题:帮我转换为js 转换之后的代码  3、拿到response返回结果data值 比如我这边想获取到toPhoneShield的值 老规矩通过文心一言提问(有条件的

    2024年01月23日
    浏览(46)
  • Python - FastAPI 实现 get、post 请求

    目录 一.引言 二.FastAPI Server 构建 1.get - read_items 2.post - create_item 3.uvicorn - run_app 三.Postman 请求 1.post - create_item 2.get - read_items 四.Requests 请求 1.post - create_item 2.get - read_items 五.总结 前面介绍了 LLM 的相关知识,从样本加载、模型加载到后面的模型训练与模型推理,我们经历的完

    2024年02月05日
    浏览(28)
  • Qt实现HTTP的Get/Post请求

    借助Qt的NetWork模块,可以轻松的实现HTTP的Get/Post请求,而不需要再次引用像libcurl这样的第三方库。 当然,Qt的NetWork模块提供的功能远远不只是HTTP方面的。 另外,使用Qt网络模块还需要引用Qt5Network.lib库。 先构造一个QNetworkAccessManager对象,QNetworkAccessManager对象提供了发送QNe

    2024年02月07日
    浏览(39)
  • C语言通过IXMLHTTPRequest以get或post方式发送http请求获取服务器文本或xml数据

    做过网页设计的人应该都知道ajax。 Ajax即Asynchronous Javascript And XML(异步的JavaScript和XML)。使用Ajax的最大优点,就是能在不更新整个页面的前提下维护数据。这使得Web应用程序更为迅捷地回应用户动作,并避免了在网络上发送那些没有改变的信息。 在IE浏览器中,Ajax技术就是

    2024年01月25日
    浏览(41)
  • curl c++ 实现HTTP GET和POST请求

    环境配置 curl //DV2020T环境下此步骤可省略 https://curl.se/download/ 笔者安装为7.85.0版本 ./configure --without-ssl make sudo make install sudo rm /usr/local/lib/curl 系统也有curl库,为防止冲突,删去编译好的curl库。 对以json数据的解析使用开源项目:https://github.com/nlohmann/json cd single_include 在这个文

    2024年03月12日
    浏览(48)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包