android调取api接口

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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值