百度翻译api(接口)--使用post请求--java后台--只需三步

4 篇文章 0 订阅

一:前言

这篇文章主要是讲给需要用百度翻译api做产品的人,下面肯定不会将怎么申请百度翻译api,怎么用,因为这一些你在网上搜(百度等等)是有很多的,主要我是讲在用百度翻译api的时候,怎么让java使用post请求去请求百度翻译的接口,从而避免get请求带来的414和返回null

二:场景模拟

公司产品准备上线了,翻译这一模块是直接用百度翻译提供的api的demo直接用,用户某一天用一个超长的文本去翻译,发现返回值为null,查看后台才知道是请求出错414url地址过长,然后第一时间就想到不能get请求,要用post请求,当我去百度或者其他的搜索引擎去搜结果的时候,发现用java的post请求去请求百度翻译api的寥寥无几。就准备自己琢磨去修改一下代码


三:步骤分析

首先我们下载的demo有这三个核心文件,一个是负责请求的,一个负责加密,一个负者业务处理。

所以我们需要在HttpGet.java去增加一个post请求

步骤一:在HttpGet中增加一个post请求,当然这个你也可以自己去写一个类HttpPost来写post请求,这里是直接在HttpGet.java中增加的post

1.post方法:主要是负责post请求,包括传递参数。

2.convertStreamToString方法:主要是对post请求返回的结果进行处理,转换为一个String对象

步骤二:编写post方法,参数url主要是请求地址,param主要是需要传递的参数,我是一个map,你们自己可以为String或者其他的,这里主要是明白一下几点

1.

httpURLConnection.setDoOutput(true);//此申明在申明请求方式为post之前
httpURLConnection.setRequestMethod("POST");//申明请求为post

2.

httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//后面的application/x-www-form-urlencoded主要能我们传递参数的时候为name=jc&age=54&sex=2这种get形式来传递参数
httpURLConnection.setRequestProperty("Content-Length", String.valueOf("5000"));//设置传递文件的长度

3.

outputStreamWriter.write(builder.toString());主要这里是向请求地址去传递参数

步骤三:编写convertStreamToString,主要一个参数就是inputStream,输入流,来解析结果


四:HttpGet.java完整代码

package cn.cigit.contextquery.servlet;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

class HttpGet {
    protected static final int SOCKET_TIMEOUT = 10000; // 10S
    protected static final String GET = "GET";
    protected static final String POST = "POST";

    public static String get(String host, Map<String, String> params) {
        try {
            System.out.println("开始处理");
            // 设置SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);

            String sendUrl = getUrlWithQueryString(host, params);

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

            URL uri = new URL(sendUrl); // 创建URL对象
            URLConnection urlConnection=uri.openConnection();
            HttpURLConnection conn = (HttpURLConnection)urlConnection;
            if (conn instanceof HttpsURLConnection) {
                ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
            }

            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf("1532"));
            conn.setConnectTimeout(10000);
            conn.setDoInput(true);
            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 = null;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }

            String text = builder.toString();

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

            return text;
        } catch (MalformedURLException e) {
            System.out.println(e.toString());
        } catch (IOException e) {
            System.out.println(e.toString());
        } catch (KeyManagementException e) {
            System.out.println(e.toString());
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e.toString());
        }

        return null;
    }

    public static String getUrlWithQueryString(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            builder.append("&");
        } else {
            builder.append("?");
        }

        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();
    }

    protected static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static String encode(String input) {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return input;
    }

    private static TrustManager myX509TrustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };
    public static String post(String url, Map<String,String> param) throws Exception {

        URL localURL = new URL(url);
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf("5000"));
        httpURLConnection.setConnectTimeout(10000);

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        String resultBuffer = "";

        try {
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);


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

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

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

                i++;
            }
            outputStreamWriter.write(builder.toString());
            outputStreamWriter.flush();

            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception(
                        "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            inputStream = httpURLConnection.getInputStream();
            resultBuffer = convertStreamToString(inputStream);
            System.out.println(resultBuffer);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }

            if (outputStream != null) {
                outputStream.close();
            }

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }

        return resultBuffer;
    }

    public static String convertStreamToString(InputStream is) {
        StringBuilder sb1 = new StringBuilder();
        byte[] bytes = new byte[4096];
        int size = 0;

        try {
            while ((size = is.read(bytes)) > 0) {
                String str = new String(bytes, 0, size, "UTF-8");
                sb1.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb1.toString();
    }

}

注意你可能需要修改的地方,post请求中的param参数的类型,主要我是一个map数据,你可能是String,但是里面组装数据也需要修改。还有就是TransApi.java中把

HttpGet.get(TRANS_API_HOST, params);改为HttpGet.post(TRANS_API_HOST, params);

基本到这里就结束了,不懂的小伙伴可以加我微信:y958231955

也可以添加微信公众号:程序员PG

回复:百度翻译post

就可以下载源码了

886~

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值