1

我目前正在尝试从此 API 获取天气状况的类型,以在我的主要活动中设置图像。目前它只返回null,我试图找到问题所在,但我很挣扎。有什么帮助吗?

package soft233.helicoptercity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;


public class FetchWeather {

public static final String OPEN_WEATHER_MAP_API = "http://api.openweathermap.org/data/2.5/weather?q=%s";

public static JSONObject getJSON( String city){

    try{
        URL url = new URL(String.format(OPEN_WEATHER_MAP_API,city));
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        System.out.println(connection.toString());
        //connection.addRequestProperty("x-api-key", "8b7bd8d8b68d2b808cffaf0045f5df4e");

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        StringBuffer json = new StringBuffer();

        String temp = null;

        while((temp=reader.readLine())!=null){
            System.out.println(temp);
            json.append(temp).append("\n");

        }

        reader.close();

        JSONObject data = new JSONObject(json.toString());

        if(data.getInt("cod")!=200){
            System.out.println("no data got");
            return null;
        }

        return data;

    }catch(Exception e){

        return null;
    }
}

public static String getWeather(){

    final JSONObject json = FetchWeather.getJSON("Newcastle,GB");


    if(json!=null){
        try {
            JSONObject jsonMain = json.getJSONObject("weather");

            if(jsonMain.getString("main")=="Clouds"){
                System.out.println(json.getString("main"));
                return "Clouds";
            }
            else{
                System.out.println(json.getString("main"));
                return "Clear";

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    else{System.out.println("no json");}


    //System.out.println("no json");

    return null;
}
}
4

0 回答 0