android调取api接口简单记录一下,本文章实现了调用api达到图像上传的功能,并实现了图像识别,图像识别及python服务端代码见如下链接
https://blog.csdn.net/Low__Profile/article/details/136635424?spm=1001.2014.3001.5502
/**
* 上传照片
*/
public void upload(String filePath) {
new Thread(new Runnable() {
@Override
public void run() {
// 创建OkHttpClient实例
OkHttpClient client = new OkHttpClient();
// 准备文件(图片)
File file = new File(filePath);
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
// 创建MultipartBody.Part
MultipartBody.Part part = MultipartBody.Part.createFormData("file_imgs", file.getName(), fileBody);
// 创建请求体
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(part)
// 如果有其他参数需要上传可以这样添加
// .addFormDataPart("other_field", "other_field_value")
.build();
// 构建请求
Request request = new Request.Builder()
.url("http://192.168.43.13:5006/api/upload") // 替换为实际的API地址
.post(requestBody)
.build();
// 发送请求
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 请求失败处理
uploadImageResult.setText("失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code() == 200) {
String result = response.body().string();
String ImageForecastResult = cutString(result);
uploadImageResult.setText("预测结果为:"+ImageForecastResult);
// 请求成功处理,例如解析response.body().string()
} else {
// 请求失败处理,例如获取错误信息
}
}
});
}
}).start();
}

2253

被折叠的 条评论
为什么被折叠?



