需求
用占星术来预测每天的运程。
思路
这个真没啥说的,调用API就行,传入参数看API的需求
直接看gpt生成的代码
实现
首先加json转换的依赖:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
然后是代码:
public class AstrologyChart extends JFrame {
private static final String API_URL = "https://aztro.sameerkumar.website?sign=%s&day=today";;
private JComboBox<String> signComboBox;
private JTextArea horoscopeTextArea;
private JButton fetchButton;
public AstrologyChart() {
setTitle("Daily Horoscope");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
String[] signs = {
"aries", "taurus", "gemini", "cancer", "leo", "virgo",
"libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces"
};
signComboBox = new JComboBox<>(signs);
add(signComboBox, BorderLayout.NORTH);
horoscopeTextArea = new JTextArea();
horoscopeTextArea.setLineWrap(true);
horoscopeTextArea.setWrapStyleWord(true);
horoscopeTextArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(horoscopeTextArea);
add(scrollPane, BorderLayout.CENTER);
fetchButton = new JButton("Fetch Horoscope");
fetchButton.addActionListener(e -> fetchHoroscope());
add(fetchButton, BorderLayout.SOUTH);
}
private void fetchHoroscope() {
String selectedSign = (String)signComboBox.getSelectedItem();
String questUrl = String.format(API_URL, selectedSign);
try {
String response = ApiUtils.getApiResponse(questUrl);
JSONObject jsonObject = new JSONObject(response);
String description = jsonObject.getString("description");
horoscopeTextArea.setText(description);
} catch (Exception e) {
System.out.println(e.getMessage());
horoscopeTextArea.setText("Failed to fetch horoscope.");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new AstrologyChart().setVisible(true));
}
}
这里的ApiUtils.getApiResponse(questUrl)是之前提过的重复代码封装的工具类,代码如下:
public class ApiUtils {
public static String getApiResponse(String questUrl) throws Exception {
URL url = new URL(questUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder content = new StringBuilder();
while((line = reader.readLine()) != null){
content.append(line);
}
reader.close();
connection.disconnect();
return content.toString();
}
}