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类文章来源:https://www.toymoban.com/news/detail-627256.html
<?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模板网!