首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Weather API和HttpURLConnection

Weather API和HttpURLConnection
EN

Stack Overflow用户
提问于 2016-09-29 08:18:56
回答 1查看 263关注 0票数 0

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

MainActivity.java

代码语言:javascript
复制
//..... (previous codes obtain the coordinate, and working)
RetrieveWeather mRetrieveWeather = new RetrieveWeather();
t.append("" + mRetrieveWeather.getWeatherReport(mCoordinate));

RetrieveWeather.java

代码语言:javascript
复制
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都会显示“你又失败了!”。

为什么?

(附注:我在Manifest中确实有足够的用户权限)

EN

回答 1

Stack Overflow用户

发布于 2016-09-29 08:24:29

我建议使用一个库来提出你的网络请求,这将为你省去很多麻烦。以http://square.github.io/retrofit/为例查看Retrofit

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39759492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档