Baidu translation API usage tutorial (front-end + back-end)

1. Qualification acquisition

First, we need to log in to the Baidu Translation Open Platform to obtain the developer qualification:

access

Baidu translation open platform

Then register (if you have a Baidu account, you can log in directly)

After successful registration, click "Product Service":

Jump to the general text API interface:

Click "Use Now" at the bottom of the page to select the service to use

The Generic Text API has three services to choose from:

Individual users can use the first two, and the use of the advanced version requires personal authentication (real-name authentication)

2. Easy to use

Click "Management Console" to open the "Developer Information" interface:

You can see your APP ID and key information, which need to be used when calling the interface;

Click the general text translation in "My Services" to see the service usage and details

If you have special requirements for translated terms, you can click "My Corpus" and create a new term base:

In this way, the terms we set can interfere with the translation results;

3. Programming implementation

Baidu translation open platform

Go to the above URL to view the development documentation of the general translation API

3.1 Front-end code

Development environment: Vue.js + Uniapp

(Uniapp quick start: uni-app official website )

Accept the input content through a text input box, and then call the backend interface for translation:

<template>
  <view>
    <!--输入框-->
		<uni-easyinput 
		type="textarea"  
		v-model="translate_source" 
		placeholder="请输入想要翻译的内容"
		suffixIcon="search"
		borderColor="grey"
		@input="input"></uni-easyinput>
  	<!--翻译按钮-->
  	<button type="primary" class="translate_button" @click="translate">开始翻译</button>
    <!--翻译内容展示-->
    <view style="margin-top: 50rpx;">
			<uni-section title="翻译内容如下:" type="line" class="translate_line">
			<view class="translate_answer">
				<textarea disabled="true" :value="translated_content"></textarea>
			</view>
			</uni-section>
		</view>
  </view>
</template>

<script>
	export default {
		data() {
			return {
				translate_source:"",
				translated_content:""
			}
		},
		methods: {
			translate()
			{
				var q = this.translate_source
				var from = "en"
				var to = "zh"
				
				var url = "http://localhost:8081/translate"
				if (q.length == 0)
				{
					uni.showModal({
						title:"错误!",
						content:"输入内容不能为空!",
						complete() {
							this.translate_source = ""
						}
					})
				}
				else{
					let that = this
					uni.request({
						url:url,
						method:"POST",
						data:{
							q:q,
							from:from,
							to:to
						},
						success(e) {
							var result = e.data.trans_result[0].dst;
							that.translated_content = result;
						},
						fail(){
							uni.showModal({
								title:"错误!",
								content:"网络错误!",
								complete() {
									this.translate_source = ""
								}
							})
						}
					})
				}
			}
		}
	}
</script>
  

The request parameters that need to be passed to the backend are:

3.2 Backend code

Development environment: springboot + Hutools

I am using the official version of idea. The community version of springBoot needs to be built by myself. You can search for the construction tutorial by yourself. If you need to use the official version of idea, you can refer to the address in the comment area to download;

First create the springBoot project:

The warehouse management and JDK version depend on your own situation. In this example, the Maven warehouse is used, JDK17;

The default version of SpringBoot is enough, you can check Spring Web:

Note: Springboot version 3.1.0 may need to use JDK17

If you use Maven, you need to install maven locally. Go to file-settings-Mavens to check whether there is local maven. If you need to modify it, change the path of maven and the path of the settings.xml configuration file; I will not repeat the installation of maven here, other tutorials Many, if you encounter any problems, you can leave a message

Secondly, if you encounter problems with the JDK version, you can open the file-project Structure to view the JDK and SDK versions of the project and modules

Make sure that the version is unified (because if you have installed multiple versions of JDK, there may be problems during initialization)

After the configuration is complete, you can start the Application to check whether it is normal

Then import Hutools dependencies in the pom.xml file:

<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.7.16</version>
</dependency>

(Hutools is a Java tool library, which is still very easy to use)

Then you can develop the interface, the code is as follows:

@RestController
public class TranslationController {

    @PostMapping("/translate")
    public Object translate(@RequestBody Map<String,String> data)
    {
        //获取请求参数
        String q = data.get("q");
        String from = data.get("from");
        String to = data.get("to");
        //随机数
        Random random = new Random(10);
        String salt = Integer.toString(random.nextInt());
        //MD5加密
        //自定义的全局变量 appid和密钥
        String appid = BaiduContent.APPID + q + salt + BaiduContent.SECRET;
        String sign = SecureUtil.md5(appid);

        //封装请求参数
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("q",q);
        paramMap.add("from",from);
        paramMap.add("to",to);
        paramMap.add("appid",BaiduContent.APPID);
        paramMap.add("salt",salt);
        paramMap.add("sign",sign);
        String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        //封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);

        //调用百度翻译API,发送请求,得到结果
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

        return response.getBody();
    }
    
}

First accept the request parameters from the front end, and then refer to the development document;

The parameters of the request translation interface are as follows:

The setting development document of sign is also written in detail:

The POST request method is used in the sample code, pay attention to configure according to the requirements in the development document:

After the interface request is successful, the translation result can be obtained and returned to the front end for display

4. Results display

Enter the content - click translate - display the translation result

If you have any questions, please leave a message to discuss, the author is also a beginner, please correct me if there are mistakes~

Guess you like

Origin blog.csdn.net/qq_51235856/article/details/131147340