安桌开发中怎么调用API接口,我的接口为"https://yurl6.cn/user/api.php" 请求方式为post,提交信息为“curl=text2”,返回值用result返回,并帮我规避app闪退问题,以及返回信息用toast提示出来,要求用okhttp库,帮我把2需要引入的包也给我列出来。
时间: 2023-12-03 20:47:37 浏览: 33
首先需要在你的安卓项目中引入OkHttp库,可以在build.gradle文件中添加以下代码:
```
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
}
```
接着,在调用API接口前,需要在AndroidManifest.xml文件中添加网络权限:
```
<uses-permission android:name="android.permission.INTERNET" />
```
下面是一个示例代码,实现了调用API接口,并将返回值用Toast提示出来:
```
// 1. 构建请求体
RequestBody requestBody = new FormBody.Builder()
.add("curl", "text2")
.build();
// 2. 构建请求
Request request = new Request.Builder()
.url("https://yurl6.cn/user/api.php")
.post(requestBody)
.build();
// 3. 发送请求
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 请求失败,处理异常
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 请求成功,处理返回值
final String result = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在UI线程中显示Toast
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}
});
```
需要注意的是,在回调函数中更新UI需要在UI线程中进行,否则会抛出异常。因此需要使用runOnUiThread方法来更新Toast。