调用百度翻译接口实现翻译:
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class MainFrame extends JFrame {
private JTextField inputField;
private JButton translateButton;
private JTextArea resultArea;
private JRadioButton enZhButton;
private JRadioButton zhEnButton;
public MainFrame() {
setTitle("Translation App");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
inputField = new JTextField();
panel.add(inputField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
enZhButton = new JRadioButton("English to Chinese", true);
zhEnButton = new JRadioButton("Chinese to English");
ButtonGroup group = new ButtonGroup();
group.add(enZhButton);
group.add(zhEnButton);
buttonPanel.add(enZhButton);
buttonPanel.add(zhEnButton);
panel.add(buttonPanel, BorderLayout.CENTER);
translateButton = new JButton("Translate");
translateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
translateText();
}
});
panel.add(translateButton, BorderLayout.SOUTH);
resultArea = new JTextArea();
panel.add(resultArea, BorderLayout.SOUTH);
add(panel);
setVisible(true);
}
private void translateText() {
String textToTranslate = inputField.getText();
String fromLanguage = "en";
String toLanguage = "zh";
if (zhEnButton.isSelected()) {
fromLanguage = "zh";
toLanguage = "en";
}
try {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"from\":\"" + fromLanguage + "\",\"to\":\"" + toLanguage + "\",\"q\":\"" + textToTranslate + "\"}");
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=24.d00144c704ef1210078015a55ebf2110.2592000.1704453000.282335-44444008")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = Sample.HTTP_CLIENT.newCall(request).execute();
String translatedText = response.body().string();
resultArea.setText(translatedText);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame();
}
});
}
}