Reputation: 81
I am working on a project where i am creating a java app for watering plants.The idea to get weather information from online and based on that output should be if we plants require water or not.For weather information,i found an API OpenWeatherMap and i tried to implement it using educational video from YouTube.I don't have past experience with API's. The video i am using is "https://www.youtube.com/watch?v=og5h5ppwXgU" .I tried to implement my program the same way that guy did,but i am not getting any output.It just prints what's in the print statements ,not the actual data.
public static Map<String,Object> jsonToMap(String str){
Map<String,Object> map = new Gson().fromJson(str,new
TypeToken<HashMap<String,Object>> () {}.getType());
return map;
}
public static void main(String[] args) {
String API_KEY = "16 digit Private Key";
String LOCATION = "Los Angeles,CA";
String urlString = "http://api.openweathermap.org/data/2.5/weather?
q=" + LOCATION + "&appid=" + API_KEY + "&units =imperial";
try{
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader (conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null){
result.append(line);
}
rd.close();
System.out.println(result);
Map<String, Object > respMap = jsonToMap (result.toString());
Map<String, Object > mainMap = jsonToMap (respMap.get("main").toString());
Map<String, Object > windMap = jsonToMap (respMap.get("wind").toString());
System.out.println("Current Temperature: " + mainMap.get("temp") );
System.out.println("Current Humidity: " + mainMap.get("humidity") );
System.out.println("Wind Speed: " + windMap.get("speed") );
System.out.println("Wind Angle: " + windMap.get("deg") );
}catch (IOException e){
System.out.println(e.getMessage());
}
}
I received errors that gson library doesn't exist ,but after i cretaed my own library in net beans with javadoc,class path and soureces,the problem got resolved ,so i think that correct.Also the API key for openweathermap is also valid.I am just not able to get the code to get online information.
Output :
http://api.openweathermap.org/data/2.5/weatherq=Los Angeles,CA&appid="16 digit Private Key"&units =imperial
Expected Output : Current weather information of LA
Upvotes: 0
Views: 8513
Reputation: 1963
Implementation of OpenWeatherMapApi with given latitude and longitude. For Network request Retrofit & Jsonschema2pojo to create model. Hope this will help.
public void getWeatherDetails(double latitude, double longitude) {
String url = "http://api.openweathermap.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url) //This is the only mandatory call on Builder object.
.addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
.build();
WeatherApiService weatherApiService = retrofit.create(WeatherApiService.class);
weatherApiService.requestWeather(String.valueOf(latitude), String.valueOf(longitude), "metric", "10").enqueue(new UpasargaCallback<WeatherModel>() {
@Override
public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
if (getView() != null) {
getView().onWeatherApiSuccess(response.body());
}
}
}
}
@Override
public void onFailure(Call<WeatherModel> call, Throwable t) {
if (getView() != null) {
getView().onWeatherApiFailure(String.valueOf(t.getMessage()));
}
}
});
}
WeatherApiService
public interface WeatherApiService {
@Headers("x-api-key: " + AppConstants.WEATHER_API_KEY)
@GET("data/2.5/forecast")
Call<WeatherModel> requestWeather(@Query("lat") String lat,@Query("lon") String lon,@Query("units") String units,@Query("cnt") String count);
}
Upvotes: 3
Reputation: 26
I tested the API with your app key in the browser. It was successful. Maybe you should encode your URL. It has a blank space which is a special character.
Upvotes: 1