Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.2 kB
5
Indexable
Never
// Replace YOUR_API_KEY with your actual API key
String apiKey = "YOUR_API_KEY";

// Set the query parameter to the text entered in the search bar
String query = "San Francisco";

// Create the URL for the search request
String url = "https://api.weatherapi.com/v1/search.json?key=" + apiKey + "&q=" + query;

// Make the HTTP request
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");

// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    response.append(line);
}
reader.close();

// Parse the JSON response
JSONObject json = new JSONObject(response.toString());

// Get the list of cities from the response
JSONArray cities = json.getJSONArray("results");

// Iterate through the list of cities
for (int i = 0; i < cities.length(); i++) {
    JSONObject city = cities.getJSONObject(i);
    String name = city.getString("name");
    String country = city.getString("country");
    // Add the city to the list of search results
}