JAVA/Andorid调用HTTP接口示例及问题总结
于燕松_ 发布于2017-03 浏览:2811 回复:3
0
收藏

import sun.misc.BASE64Encoder;

import java.io.*;

import java.net.*;


public class Main {


    public static void main(String[] args) throws IOException {

        String filePath = "image.jpg";

        URL realUrl = new URL("https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=your_access_token");

        HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();

        connection.setRequestMethod("POST");

        connection.setDoOutput(true);

        String body = String.format("id_card_side=front&image=%s", URLEncoder.encode(new BASE64Encoder().encode(readImage(filePath)).replaceAll("\r|\n", "")));

        connection.getOutputStream().write(body.getBytes("UTF-8"));

        connection.connect();

        System.out.println(

                new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine()

        );

    }


    public static byte[] readImage(String filePath){

        File file = new File(filePath);

        byte[] content = new byte[new Long(file.length()).intValue()];

        try {

            FileInputStream in = new FileInputStream(file);

            in.read(content);

            in.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return content;

    }

}


问题注意事项:

1. sun.misc.BASE64Encoder返回的编码含有换行回车,请使用.replaceAll("\r|\n", "")将其替换,否则无法识别。

2. HTTP body 里面参数值一定要经过URLEncoder.encode,否则无法识别。

收藏
点赞
0
个赞
共3条回复 最后由用户已被禁言回复于2022-04
#4追星逐月的家回复于2018-08

对于新手可以参考

0
#3hefeitest回复于2018-07

感谢大神总结经验啊

0
#2周俊316回复于2017-05

感谢分享,大家可参考哦

0
TOP
切换版块