Skip to content

Instantly share code, notes, and snippets.

@YuukiToriyama
Created June 22, 2022 07:22
Show Gist options
  • Save YuukiToriyama/76ab77c394e6e0ac97e4db5d19faf542 to your computer and use it in GitHub Desktop.
Save YuukiToriyama/76ab77c394e6e0ac97e4db5d19faf542 to your computer and use it in GitHub Desktop.
お天気アプリ
package org.example;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Main {
private static String inputStream2String(InputStream stream) {
String result = "";
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
String line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
reader.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
public static void main(String[] args) {
String response = "";
String url = "https://api.openweathermap.org/data/2.5/weather?q=Osaka&lang=ja&units=metric&appid=fcb3f4b5b7a06bc9d509d4c4fdfa5e89";
try {
URL urlObject = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
connection.setConnectTimeout(1000);
connection.setReadTimeout(1000);
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
response = inputStream2String(stream);
stream.close();
connection.disconnect();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
JSONObject json = new JSONObject(response);
String cityName = json.getString("name");
System.out.println(cityName + "の天気");
JSONObject weather = json.getJSONArray("weather").getJSONObject(0);
System.out.println("天気は" + weather.getString("description"));
Double temperature = json.getJSONObject("main").getDouble("temp");
System.out.println("気温は" + temperature);
/**
* 大阪市の天気
* 天気は曇りがち
* 気温は29.1
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment