天气api连接崩溃

时间:2015-04-25 19:26:39

标签: java android api weather-api openweathermap

我试图通过openweathermap api获得当前的风速。 我尝试了几种方法来按地理坐标获取当前天气。 这是我第一次使用api,我无法理解为什么它会一直崩溃。 如果你能帮助我,我会很棒。 :)

lat / long是当前位置。

public String GetWind(String lat, String lng) {//
        String w_speed = "0";

        try {
            URL url = null;
            url = new URL(C.WEATHER_API + "lat=" + (int) Double.parseDouble(lat) + "&lon=" + (int) Double.parseDouble(lng));
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                InputStreamReader  in = new InputStreamReader(urlConnection.getInputStream());
                BufferedReader br = new BufferedReader(in);
                String result = br.readLine();
                return w_speed;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            finally {
                urlConnection.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

根据openweathermap,这是我从api开始的json格式。

{"coord":{"lon":139,"lat":35},"sys":{"message":1.473,"country":"JP","sunrise":1429905589,"sunset":1429953850},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"stations","main":{"temp":288.106,"temp_min":288.106,"temp_max":288.106,"pressure":1026.09,"sea_level":1034.25,"grnd_level":1026.09,"humidity":100},"wind":{"speed":4.55,"deg":11.0004},"clouds":{"all":0},"dt":1429989748,"id":1851632,"name":"Shuzenji","cod":200}

with stacktrace:

04-26 00:31:59.320    8686-8686/com.matchrace.matchrace W/System.err﹕ android.os.NetworkOnMainThreadException
04-26 00:31:59.325    8686-8686/com.matchrace.matchrace W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
04-26 00:31:59.330    8686-8686/com.matchrace.matchrace W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-26 00:31:59.330    8686-8686/com.matchrace.matchrace W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-26 00:31:59.330    8686-8686/com.matchrace.matchrace W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-26 00:31:59.330    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
04-26 00:31:59.335    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
04-26 00:31:59.335    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
04-26 00:31:59.335    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
04-26 00:31:59.335    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
04-26 00:31:59.335    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
04-26 00:31:59.335    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
04-26 00:31:59.340    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
04-26 00:31:59.340    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
04-26 00:31:59.340    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.matchrace.matchrace.MainActivity.GetWind(MainActivity.java:157)
04-26 00:31:59.340    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.matchrace.matchrace.MainActivity.onLocationChanged(MainActivity.java:202)
04-26 00:31:59.340    8686-8686/com.matchrace.matchrace W/System.err﹕ at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:279)
04-26 00:31:59.340    8686-8686/com.matchrace.matchrace W/System.err﹕ at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:208)
04-26 00:31:59.345    8686-8686/com.matchrace.matchrace W/System.err﹕ at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:224)
04-26 00:31:59.345    8686-8686/com.matchrace.matchrace W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 00:31:59.345    8686-8686/com.matchrace.matchrace W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
04-26 00:31:59.345    8686-8686/com.matchrace.matchrace W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5034)
04-26 00:31:59.345    8686-8686/com.matchrace.matchrace W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-26 00:31:59.345    8686-8686/com.matchrace.matchrace W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
04-26 00:31:59.345    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
04-26 00:31:59.350    8686-8686/com.matchrace.matchrace W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
04-26 00:31:59.350    8686-8686/com.matchrace.matchrace W/System.err﹕ at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
04-26 00:31:59.350    8686-8686/com.matchrace.matchrace W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

使用asynctask或网络库如volley,loopj等以下是asynctask的例子

class LongOpreation extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {

    String str = "";

    try {
        str = sendGetRequest();

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return str;
}

public String sendGetRequest() throws MalformedURLException {
    StringBuilder response = new StringBuilder();
    String requrl = "";
    requrl = C.WEATHER_API + "lat=" + (int) Double.parseDouble(lat) + "&lon=" + (int) Double.parseDouble(lng);
    response = requestExecuter(requrl);


    return response.toString();

}


@Override
protected void onPostExecute(String result) {
    try {
        JSONObject jsonObject = new JSONObject(result);
        System.out.println("json-----------------------"+jsonObject);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

@Override
protected void onPreExecute() {

}
public StringBuilder requestExecuter(String str) {
    StringBuilder response = new StringBuilder();
    try {
        URL url = new URL(str);

        HttpURLConnection httpconn = (HttpURLConnection) url
                .openConnection();
        httpconn.setConnectTimeout(5000);
        httpconn.setReadTimeout(10000);

        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpconn.getInputStream()));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);

            }
            input.close();
        }
        } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return response;
}
  }

你也可以将参数传递给asynctask并调用asynctask,如下所示

new LongOperation().execute("");//with empty string as parameter