欢迎光临
感受代码之美

通过OkHttp上传图片示例

背景:通过OkHttp上传头像照片,调用旷世人脸识别1:n静态识别API接口,识别人脸信息。

  • OkHttp: version: ‘4.9.0’

实现代码:

/**
     * 面部识别
     *
     * @param imageFile   人脸图片,必传
     * @param screenToken 设备token,非必传
     * @return
     */
    public static String faceRecognize(File imageFile, String screenToken) {
        String url = "http://192.168.1.50:8866/recognize";

        RequestBody fileBody = RequestBody.create(imageFile, MediaType.parse("image/png"));
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                //可以根据自己的接口需求在这里添加上传的参数
                .addFormDataPart("image", "avatar", fileBody)
                .addFormDataPart("screen_token", screenToken)
                .build();

        Request request;
        Call call;
        Response response;
        try {
            request = new Request.Builder()
                    .url(url)
                    .addHeader("Content-Type", "multipart/form-data")
                    .post(requestBody)
                    .build();

            call = new OkHttpClient().newCall(request);
            response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
赞(0)
未经允许禁止转载:四个空格 » 通过OkHttp上传图片示例

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址