谈谈百度翻译的坑(Java)

百度翻译API肯定有很多人在用,但是就算是百度这样的大公司也会有很多的坑

1:MD5内的坑

 try {
            // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 输入的字符串转换成字节数组
            byte[] inputByteArray = input.getBytes("utf-8");
            // inputByteArray是输入字符串转换得到的字节数组
            messageDigest.update(inputByteArray);
            // 转换并返回结果,也是字节数组,包含16个元素
            byte[] resultByteArray = messageDigest.digest();
            // 字符数组转换成字符串返回
            return byteArrayToHex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }

这个MD5的类少catch了一个UnsupportedEncodingException编译报错

2:httpget类的坑

这里用的是get方法所以传参方式是url传值,但是需翻译的内容比较大时
414(“Request-URI Too Long”)异常
详情见这篇博客
所以要将此改为post方法,可避免此异常
改动后的代码

class HttpPost {
    private static final int SOCKET_TIMEOUT = 10000; // 10S
    private static final String POST = "POST";

    static String post(String host, Map params) {
        try {
            // 设置SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);

            // System.out.println("URL:" + sendUrl);

            URL uri = new URL(host); // 创建URL对象
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(SOCKET_TIMEOUT); // 设置相应超时
            conn.setRequestMethod(POST);
            if (conn instanceof HttpsURLConnection) {
                ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
            }

            OutputStream outputStream = conn.getOutputStream();
            String data = getUrlWithQueryString(params);//拼装参数
            outputStream.write(data.getBytes());//上传参数

            int statusCode = conn.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
                System.out.println("Http错误码:" + statusCode);
            }

            // 读取服务器的数据
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }

            String text = builder.toString();

            close(br); // 关闭数据流
            close(is); // 关闭数据流
            conn.disconnect(); // 断开连接

            return text;
        } catch (IOException | KeyManagementException | NoSuchAlgorithmException e) {
            return null;
        }
    }

    private static String getUrlWithQueryString(Map params) {
        if (params == null) {
            return "";
        }

        StringBuilder builder = new StringBuilder();

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { // 过滤空的key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;
        }

        return builder.toString();
    }

    private static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3:访问限制的坑

百度最近一次更新增添了访问次数免费最高10次/秒所以不能使用多线程并发访问了

你可能感兴趣的:(Java)