百度机器翻译SDK实验
package com.step04; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import javax.swing.*; import java.awt.*; import java.awt.event.ItemEvent; public class TranslationGUI { private JFrame transFrame; private JButton transButton; private JTextArea sendText; private JTextArea receiveText; private JComboBox boxSendLanguage; private String sendType="自动检测"; private JComboBox boxReciveLanguage; private String receiveType="汉语"; private String[] listSendLanguage ={"自动检测","汉语","英语","俄语","日语", "韩语","法语","西班牙语","德语" ,"意大利语","葡萄牙语","越南语","印尼语" ,"马来语","泰语","阿拉伯语","印地语" ,"土耳其语","希腊语","匈牙利语"}; private String[] listReceiveLanguage ={"汉语","英语","俄语","日语", "韩语","法语","西班牙语","德语" ,"意大利语","葡萄牙语","越南语","印尼语" ,"马来语","泰语","阿拉伯语","印地语" ,"土耳其语","希腊语","匈牙利语"}; private JSONObject valuesLanguage = new JSONObject(); public TranslationGUI() throws JSONException { Translatator translatator = new Translatator(); valuesLanguage.put("自动检测", "auto"); valuesLanguage.put("汉语", "zh"); valuesLanguage.put("英语", "en"); valuesLanguage.put("俄语", "ru"); valuesLanguage.put("日语", "jp"); valuesLanguage.put("韩语", "kor"); valuesLanguage.put("法语", "fra"); valuesLanguage.put("西班牙语", "spa"); valuesLanguage.put("德语", "de"); valuesLanguage.put("意大利语", "it"); valuesLanguage.put("葡萄牙语", "pt"); valuesLanguage.put("越南语", "vie"); valuesLanguage.put("印尼语", "id"); valuesLanguage.put("马来语", "may"); valuesLanguage.put("泰语", "th"); valuesLanguage.put("阿拉伯语", "ara"); valuesLanguage.put("印地语", "hi"); valuesLanguage.put("土耳其语", "tr"); valuesLanguage.put("希腊语", "el"); valuesLanguage.put("匈牙利语", "hu"); transFrame = new JFrame("百度翻译mini版"); transFrame.setSize(800, 400); transFrame.setLocationRelativeTo(null); transFrame.setResizable(false);//不可缩放 /** * 设置窗口关闭按钮点击后的默认操作, 参考值: * WindowConstants.DO_NOTHING_ON_CLOSE: 不执行任何操作。 * WindowConstants.HIDE_ON_CLOSE: 隐藏窗口(不会结束进程), 再次调用 setVisible(true) 将再次显示。 * WindowConstants.DISPOSE_ON_CLOSE: 销毁窗口, 如果所有可显示的窗口都被 DISPOSE, 则可能会自动结束进程。 * WindowConstants.EXIT_ON_CLOSE: 退出进程。 */ transFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel bodyPanel = new JPanel(); bodyPanel.setSize(new Dimension(600, 300)); JPanel sendPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); sendPanel.setBackground(Color.GRAY); sendText = new JTextArea(11,17); sendText.setFont(new Font("微软雅黑", Font.PLAIN, 20)); sendText.setBackground(Color.WHITE); sendPanel.add(sendText); JPanel transPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); transPanel.setPreferredSize(new Dimension(100, 100)); transButton = new JButton("翻译->"); transButton.setSize(100,20); transButton.addActionListener(e -> { String request = sendText.getText(); if(sendType == receiveType){ JOptionPane.showMessageDialog(null, "无法把"+sendType+"翻译成"+receiveType); }else if(request.length() > 0){ String temp = sendText.getText(); try { receiveText.setText(translatator.getReceiveText(temp,valuesLanguage.getString(sendType),valuesLanguage.getString(receiveType))); } catch (JSONException ex) { JOptionPane.showMessageDialog(null, "翻译出现异常"); } }else{ JOptionPane.showMessageDialog(null, "请输入要翻译的内容"); } }); boxSendLanguage = new JComboBox<>(listSendLanguage); boxSendLanguage.setSize(30,20); boxSendLanguage.addItemListener(e -> { if(e.getStateChange() == ItemEvent.SELECTED){ sendType = (String) e.getItem(); System.out.println("s:"+sendType); } }); boxReciveLanguage = new JComboBox<>(listReceiveLanguage); boxReciveLanguage.addItemListener(e -> { if(e.getStateChange() == ItemEvent.SELECTED){ receiveType = (String) e.getItem(); System.out.println("r:"+receiveType); } }); transPanel.add(boxSendLanguage); transPanel.add(transButton); transPanel.add(boxReciveLanguage); JPanel receivePanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); receivePanel.setBackground(Color.GRAY); receiveText = new JTextArea(11,17); receiveText.setBackground(Color.WHITE); receiveText.setFont(new Font("微软雅黑", Font.PLAIN, 20)); receiveText.setEditable(false); receivePanel.add(receiveText); GridBagConstraints GBC = new GridBagConstraints(); GBC.gridx = 0; GBC.gridy = 0; GBC.gridwidth = 4; GBC.gridheight = 1; bodyPanel.add(sendPanel, GBC); GBC.gridx = 0; GBC.gridy = 0; GBC.gridwidth = 1; GBC.gridheight = 1; bodyPanel.add(transPanel, GBC); GBC.gridx = 0; GBC.gridy = 0; GBC.gridwidth = 4; GBC.gridheight = 1; bodyPanel.add(receivePanel, GBC); transFrame.setContentPane(bodyPanel); transFrame.setVisible(true); } public static void main(String[] args) throws JSONException { new TranslationGUI(); } }
package com.step04; import com.google.gson.JsonArray; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class Translatator { private String CLIENT_ID = "jnR7w5p8sNrvnatsXE5NrNLX"; private String API_KEY = "jnR7w5p8sNrvnatsXE5NrNLX"; private String SECRET_KEY = "aloZ33pgdYR1qnjmOhHvvX54j3C6Rchl"; public String getAccessToken() { try{ URL url = new URL("https://aip.baidubce.com/oauth/2.0/token?client_id="+API_KEY+"&client_secret="+SECRET_KEY+"&grant_type=client_credentials"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Content-Type", "application/json"); httpURLConnection.setRequestProperty("Accept", "application/json"); int responseCode = httpURLConnection.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ System.out.println("responseCode:"+responseCode); BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); System.out.println("response:"+response.toString()); JSONObject jsonObject = new JSONObject(response.toString()); return jsonObject.getString("access_token"); }else { System.out.println("responseCode:" + responseCode); } httpURLConnection.disconnect(); }catch (IOException e){ e.printStackTrace(); } catch (JSONException e) { throw new RuntimeException(e); } return null; } public String getResult(String sendText,String sendLanguage,String receiveLanguage) { try{ URL url = new URL("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token="+getAccessToken()); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Content-Type", "application/json"); httpURLConnection.setRequestProperty("Accept", "application/json"); String requestBody = "{\"from\":\""+sendLanguage+"\"," + "\"to\":" + "\"" + receiveLanguage + "\","+ "\"q\":"+ "\"" + sendText + "\"}"; //设置请求体 System.out.println(requestBody); httpURLConnection.setDoOutput(true); try(OutputStream outputStream = httpURLConnection.getOutputStream()){ byte[] input = requestBody.getBytes("UTF-8"); outputStream.write(input, 0, input.length); } int responseCode = httpURLConnection.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 输出响应数据 return response.toString(); } }catch (IOException e){ e.printStackTrace(); } return null; } public String getReceiveText(String sendText,String sendLanguage,String receiveLanguage) { try{ Translatator translatator = new Translatator(); JSONObject jsonObject1 = new JSONObject(translatator.getResult(sendText,sendLanguage,receiveLanguage)); JSONObject jsonObject2 = new JSONObject(jsonObject1.getString("result")); System.out.println(jsonObject2.toString()); JSONArray jsonArray = jsonObject2.getJSONArray("trans_result"); String dst = jsonArray.getJSONObject(0).getString("dst"); System.out.println(dst); return dst; }catch (JSONException e){ e.printStackTrace(); } return ""; } }
本次实验难点在于理解java发起http请求并获取网页返回的数据