发起请求获取json数据
导入依赖
implementation 'com.squareup.okhttp3:okhttp:4.4.1'
implementation 'com.google.code.gson:gson:2.8.6'
发起请求获取数据
Headers.Builder header = new Headers.Builder();
header.add("Content-Type", "application/x-www-form-urlencoded");
//调用后端接口,设置参数
FormBody.Builder params = new FormBody.Builder();
params.add("key", key);
params.add("version", version);
//发送请求,可以使用默认的http,这里使用okhttp请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(params.build())
.build();
Response response = client.newCall(request).execute();//执行发送的指令
//获取返回过来的参数
String responseData = response.body().string();//获取返回过来的json格式结果
Log.i("responseData", responseData);
//处理responseData
JSONObject jsonObject = new JSONObject(responseData.toString());
String reason = jsonObject.optString("reason");
Log.i("reason", reason);
JOSNObject实现对json数据的解析
// JSONObject 实现解析
try {
ArrayList<Money> li = new ArrayList<>();
JSONObject result = jsonObject.optJSONObject("result");
// 创建 JSONArray 对象
JSONArray list = result.optJSONArray("list");
// 遍历 JSONArray
for (int i = 0; i < list.length(); i++) {
// 获取数组中的每个 JSONObject
JSONObject money = list.getJSONObject(i);
// 从 JSONObject 中获取数据
String name = money.getString("name");
String code = money.getString("code");
// 打印收集数据
li.add(new Money(name, code));
}
MyResult myResult = new MyResult(reason, li, jsonObject.optString("error_code"));
Log.i("myResult", myResult.toString());
Log.i("reason", myResult.getReason());
Log.i("list", myResult.listToString());
Log.i("error_code", myResult.getError_code());
} catch (JSONException e) {
e.printStackTrace();
}
GSON实现对json数据的解析
// Gson实现解析
JSONObject result = jsonObject.optJSONObject("result");
String jsonString = result.optString("list");
// 使用 Gson 将 JSON 列表转换为 Java 对象列表
Gson gson = new Gson();
Type personListType = new TypeToken<List<Money>>() {
}.getType();
List<Money> moneyList = gson.fromJson(jsonString, personListType);
// 访问 Java 对象列表的元素
for (Money money : moneyList) {
System.out.println("Name: " + money.getName());
System.out.println("Code: " + money.getCode());
System.out.println();
}
完整代码
package com.example.exchagerate;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import com.example.exchagerate.bean.Money;
import com.example.exchagerate.bean.MyResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private String url = "http://op.juhe.cn/onebox/exchange/list";
private String key = "自己申请的key";
private String version = "2";
private String need = "result"; //参数名称
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(this::onClick);
}
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
try {
//
Headers.Builder header = new Headers.Builder();
header.add("Content-Type", "application/x-www-form-urlencoded");
//调用后端接口,设置参数
FormBody.Builder params = new FormBody.Builder();
params.add("key", key);
params.add("version", version);
//发送请求,可以使用默认的http,这里使用okhttp请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(params.build())
.build();
Response response = client.newCall(request).execute();//执行发送的指令
//获取返回过来的参数
String responseData = response.body().string();//获取返回过来的json格式结果
Log.i("responseData", responseData);
//处理responseData
JSONObject jsonObject = new JSONObject(responseData.toString());
String reason = jsonObject.optString("reason");
Log.i("reason", reason);
// JSONObject 实现解析
try {
ArrayList<Money> li = new ArrayList<>();
JSONObject result = jsonObject.optJSONObject("result");
// 创建 JSONArray 对象
JSONArray list = result.optJSONArray("list");
// 遍历 JSONArray
for (int i = 0; i < list.length(); i++) {
// 获取数组中的每个 JSONObject
JSONObject money = list.getJSONObject(i);
// 从 JSONObject 中获取数据
String name = money.getString("name");
String code = money.getString("code");
// 打印收集数据
li.add(new Money(name, code));
}
MyResult myResult = new MyResult(reason, li, jsonObject.optString("error_code"));
Log.i("myResult", myResult.toString());
Log.i("reason", myResult.getReason());
Log.i("list", myResult.listToString());
Log.i("error_code", myResult.getError_code());
} catch (JSONException e) {
e.printStackTrace();
}
// // Gson实现解析
// JSONObject result = jsonObject.optJSONObject("result");
// String jsonString = result.optString("list");
//
// // 使用 Gson 将 JSON 列表转换为 Java 对象列表
// Gson gson = new Gson();
// Type personListType = new TypeToken<List<Money>>() {
// }.getType();
// List<Money> moneyList = gson.fromJson(jsonString, personListType);
//
// // 访问 Java 对象列表的元素
// for (Money money : moneyList) {
// System.out.println("Name: " + money.getName());
// System.out.println("Code: " + money.getCode());
// System.out.println();
// }
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException | JSONException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
}
bean
package com.example.exchagerate.bean;
public class Money {
private String name;
private String code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Money(String name, String code) {
this.name = name;
this.code = code;
}
@Override
public String toString() {
return "Money{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
'}';
}
}
package com.example.exchagerate.bean;
import java.util.List;
public class MyResult {
String reason;
List<Money> list;
String error_code;
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public List<Money> getList() {
return list;
}
public String listToString(){
return list.toString();
}
public void setList(List<Money> list) {
this.list = list;
}
public String getError_code() {
return error_code;
}
public void setError_code(String error_code) {
this.error_code = error_code;
}
public MyResult(String reason, List<Money> list, String error_code) {
this.reason = reason;
this.list = list;
this.error_code = error_code;
}
@Override
public String toString() {
return "MyResult{" +
"reason='" + reason + '\'' +
", list=" + list +
", error_code='" + error_code + '\'' +
'}';
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮"/>
</androidx.constraintlayout.widget.ConstraintLayout>
manifests.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ExchageRate"
tools:targetApi="31"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>