创建一个空的Android项目
文章来源地址https://www.toymoban.com/news/detail-536960.html
- 创建成功之后在MainActivity中实现调用JavaSpring后端的接口项目,这里使用的是,实现点击一个按钮,然后发送http请求的示例
- 准备工作:Android自带的http发送请求的方法不太好用,所以我们使用okhttp方法来实现,打开,buile.gradle(Module:app),导入下面的代码
apply plugin: 'com.android.application'
android {
compileSdkVersion 33
buildToolsVersion "33.0.0"
defaultConfig {
applicationId "com.skypan.myapplication"
minSdkVersion 21
targetSdkVersion 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.squareup.okhttp3:okhttp:4.4.1'//导入这个,然后点击刷新下载,成功之后就可以使用了
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
- 首先是实现后端使用@RequestBody注解开发的接口
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//发送java 中@RequestBody注解的请求示例
Button button = findViewById(R.id.按钮id);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
//调用后端接口
String json = "json格式的body";//后端接收的body参数
//发送请求,可以使用默认的http,这里使用okhttp请求
OkHttpClient client = new OkHttpClient();//创建client对象
//发送请求
Request request = new Request.Builder()
.url("接口地址")
.post(
RequestBody
.create(
MediaType
.parse("application/json"),json))
.build();
Response response = client.newCall(request).execute();//执行发送的指令,并接收后端接口返回的数据
runOnUiThread(new Runnable() {
@Override
public void run() {
//操作安卓界面不能在单线程中,只能在主线程中,所以使用runOnUiThread中操作ui
Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e){
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
});
- 调用JavaSpring开发的参数直接放在url上的请求示例
Button button1 = findViewById(R.id.按钮id);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
//调用后端接口,设置参数
FormBody.Builder params = new FormBody.Builder();
params.add("参数名称","参数值");
//发送请求,可以使用默认的http,这里使用okhttp请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("接口地址")
.post(params.build())
.build();
Response response = client.newCall(request).execute();//执行发送的指令
//获取返回过来的参数
String responseData = response.body().string();//获取返回过来的json格式结果
JSONObject jsonObject = new JSONObject();
jsonObject.get("参数名称");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e){
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
});
- 调用JavaSpring后端开发的上传文件的接口示例
Button button2 = findViewById(R.id.按钮id);
button2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
//调用后端接口
OkHttpClient client = new OkHttpClient();
File file = new File("文件路径");//被上传的文件,注意权限
MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);//通过表单上传
RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"),file);//上传的文件以及类型
requestBody.addFormDataPart("file",file.getName(),fileBody);//参数:1请求的key,2.文件名称,3fileBody
final Request request = new Request.Builder()
.url("接口地址")
.post(requestBody.build())
.build();//创建请求
client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
Log.d("文件上传","失败了");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.isSuccessful()){
try {
JSONObject jsonObject = new JSONObject(response.body().string());
Log.d("文件上传成功",jsonObject.getString("code"));
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.d("文件上传",response.message()+"error:body"+response.body().string());
}
}
});
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e){
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
});
文章来源:https://www.toymoban.com/news/detail-536960.html
到了这里,关于Android开发,实现和后端接口交互,调用!的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!