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

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

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中使用OkHttp3进行POST和GET请求来发送数据到OneNet物联网云平台可以按照以下步骤进行。 首先,要使用OkHttp3,需要将其添加为项目的依赖项。可以在项目的build.gradle文件中添加以下代码来导入OkHttp3库: ```groovy implementation 'com.squareup.okhttp3:okhttp:3.12.1' ``` 接下来,要发送POST请求,可以使用OkHttp3的Request和RequestBody类来构建请求,并使用OkHttpClient来执行请求。 ```java OkHttpClient client = new OkHttpClient(); // 构建请求体 FormBody requestBody = new FormBody.Builder() .add("key1", "value1") .add("key2", "value2") .build(); // 构建请求 Request request = new Request.Builder() .url("https://api.heclouds.com/devices/{deviceId}/datapoints") .addHeader("api-key", "YOUR_API_KEY") .post(requestBody) .build(); // 执行请求 try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { // 请求成功 String responseData = response.body().string(); // 处理返回的数据 } else { // 请求失败 // 处理错误信息 } } catch (IOException e) { e.printStackTrace(); } ``` 上面的代码示例中,我们创建了一个FormBody作为请求体,并填充了要发送的数据请求的URL需要替换为OneNet物联网云平台实际的URL,同时需要在请求头中添加API密钥。 对于GET请求,可以使用OkHttp3的Url类来构建请求,同样使用OkHttpClient来执行请求。 ```java OkHttpClient client = new OkHttpClient(); // 构建请求 HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.heclouds.com/devices/{deviceId}/datapoints").newBuilder(); urlBuilder.addQueryParameter("key1", "value1"); urlBuilder.addQueryParameter("key2", "value2"); // 执行请求 try { Request request = new Request.Builder() .url(urlBuilder.build()) .addHeader("api-key", "YOUR_API_KEY") .get() .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { // 请求成功 String responseData = response.body().string(); // 处理返回的数据 } else { // 请求失败 // 处理错误信息 } } catch (IOException e) { e.printStackTrace(); } ``` 同样地,GET请求的URL需要替换为OneNet物联网云平台实际的URL,同时在请求头中添加API密钥。GET请求需要使用Url类来构建URL,并通过addQueryParameter()方法添加查询参数。 以上就是使用OkHttp3在Android中发送POST和GET请求到OneNet物联网云平台的简要步骤。根据实际的接口定义和需求,可能需要调整请求的参数和处理返回数据的逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值