2016-09-29 85 views
0

所以我打算做一个应用程序,为您提供当前位置的天气。现在我知道我的当前坐标,我写了下面的代码:天气API和HttpURLConnection

MainActivity.java

//..... (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!"; 
    } 
} 

注意,URL是有效的,但我取代了我的appid这里。

每次运行此代码时,TextView都会显示“您再次失败!”。

为什么?

(附注:我有内部清单足够的用户权限)

+1

你应该看看你的LogCat,但你的问题可能是一个NetworkOnMainThread异常 –

+0

有很容易的网络库使用,顺便说一句 –

回答

0

您不能在主线程网络请求。这可能是问题所在,尽管很难说没有看到结果打印堆栈跟踪。我会建议使用一个库来使你的网络请求,它会为你节省很多头痛。看看改造,例如http://square.github.io/retrofit/