每日总结11.29

百度机器翻译SDK实验
完成百度翻译GUI相关功能代码并测试调用,实现中文翻译成英文,英文翻译成中文。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package baidu.com;
 
import okhttp3.*;
import org.json.JSONObject;
 
import java.io.*;
 
class Sample {
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";
 
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
 
    public static void main(String []args) throws IOException{
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"from\":\"en\",\"to\":\"zh\"}");
        Request request = new Request.Builder()
            .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken())
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());
 
    }
     
     
    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
     
}

  

 

posted @   Espen  阅读(28)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示