Created
September 24, 2021 14:25
-
-
Save Da9el00/e8b1c2e5185e51413d9acea81056c2f9 to your computer and use it in GitHub Desktop.
How to connect to An API using Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json.simple.JSONArray; | |
import org.json.simple.JSONObject; | |
import org.json.simple.parser.JSONParser; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
/* | |
Maven dependency for JSON-simple: | |
<dependency> | |
<groupId>com.googlecode.json-simple</groupId> | |
<artifactId>json-simple</artifactId> | |
<version>1.1.1</version> | |
</dependency> | |
*/ | |
try { | |
//Public API: | |
//https://www.metaweather.com/api/location/search/?query=<CITY> | |
//https://www.metaweather.com/api/location/44418/ | |
URL url = new URL("https://www.metaweather.com/api/location/search/?query=London"); | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
conn.setRequestMethod("GET"); | |
conn.connect(); | |
//Check if connect is made | |
int responseCode = conn.getResponseCode(); | |
// 200 OK | |
if (responseCode != 200) { | |
throw new RuntimeException("HttpResponseCode: " + responseCode); | |
} else { | |
StringBuilder informationString = new StringBuilder(); | |
Scanner scanner = new Scanner(url.openStream()); | |
while (scanner.hasNext()) { | |
informationString.append(scanner.nextLine()); | |
} | |
//Close the scanner | |
scanner.close(); | |
System.out.println(informationString); | |
//JSON simple library Setup with Maven is used to convert strings to JSON | |
JSONParser parse = new JSONParser(); | |
JSONArray dataObject = (JSONArray) parse.parse(String.valueOf(informationString)); | |
//Get the first JSON object in the JSON array | |
System.out.println(dataObject.get(0)); | |
JSONObject countryData = (JSONObject) dataObject.get(0); | |
System.out.println(countryData.get("woeid")); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
mabi0110
commented
Nov 23, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment