2016-09-29 9 views
0

私はあなたの現在の場所の天気を提供するアプリを作ろうとしていました。今、私は私の現在の座標を知っている、と私は、次のコードを書きました:私は私のAPPIDを交換したが、天気APIとHttpURLConnection

MainActivity.java URLが有効であることを

//..... (previous codes obtain the coordinate, and working) 
RetrieveWeather mRetrieveWeather = new RetrieveWeather(); 
t.append("" + mRetrieveWeather.getWeatherReport(mCoordinate)); 

RetrieveWeather.java

package com.example.maest.weather; 

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

/** 
* Created by maest on 2016/9/28. 
*/ 
public class RetrieveWeather { 
     public String getWeatherReport(double[] mCoordinate){ 
     HttpURLConnection mHttpUrlConnection = null; 
     InputStream mInputStream = null; 

     try{ 
      mHttpUrlConnection = (HttpURLConnection) (new URL("http://api.openweathermap.org/data/2.5/forecast?lat=38.868884&lon=-77.053086&appid=myid)).openConnection(); 
      mHttpUrlConnection.setRequestMethod("GET"); 
      mHttpUrlConnection.setDoInput(true); 
      mHttpUrlConnection.connect(); 

      StringBuffer mStringBuffer = new StringBuffer(); 
      mInputStream = mHttpUrlConnection.getInputStream(); 
      BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream)); 
      String mString = null; 
      while ((mString = mBufferedReader.readLine()) != null) 
       mStringBuffer.append(mString + "\n"); 

      mInputStream.close(); 
      mHttpUrlConnection.disconnect(); 
      return mStringBuffer.toString(); 
     }catch (Throwable t){ 
      t.printStackTrace(); 
     }finally{ 
      try { mInputStream.close();}catch(Throwable t) {} 
      try { mHttpUrlConnection.disconnect();}catch(Throwable t) {} 
     } 

     return "You failed again!"; 
    } 
} 

注意をここに。

このコードを実行するたびに、TextViewに「もう一度失敗しました!」と表示されます。

なぜですか?

(私はマニフェスト内の十分なユーザー権限を持っているP.S.)

+1

あなたはLogCatを見てくださいが、おそらくNetworkOnMainThreadの例外です –

+0

ところで、使用するネットワークライブラリはずっと簡単です –

答えて

0

あなたは、メインスレッド上のネットワーク要求をすることはできません。これはおそらく問題ですが、スタックトレースの結果を見ることなく言うのは難しいですが。あなたの頭痛の多くを保存するネットワーク要求をするためにライブラリを使用することをお勧めします。レトロフィットを見てくださいhttp://square.github.io/retrofit/