您的位置:首页 > 移动开发 > Android开发

android开发练习

2016-02-25 09:24 435 查看
 引用 http://blog.csdn.net/jediael_lu/article/details/25811579仿照这篇文章写一个类似的程序程序碰上的问题一api更换;查询之后获取最新apiapi.openweathermap.org/data/2.5/weather?q=London问题2java.io.FileNotFoundException: http://api.openweathermap.org/data/2.5/weather?q=London  
url1 = "api.openweathermap.org/data/2.5/weather?q="+location.getText().toString()+",uk&appid=44db6a862fba0b067b1930da0d769e98";
原来是需要apikey
改完之后依然是问题2,进行debug
发现问题出在这里URL url = new URL(url1 );
修改为
URL url = new URL("https://"+url1);
之后成功运行,但输出结果全是0.
发现问题
org.json.JSONException: End of input at character 0 of 
改写部分语句
//等待上述线程完成执行后再返回jsonText。
try {Thread.sleep(1000);return jsonText;} catch (InterruptedException e) {e.printStackTrace();}return null;
java.net.SocketTimeoutException: failed to connect to api.openweathermap.org/192.241.169.168 (port 443) after 15000ms
加了很多断点进入debug查看,发现主线程已经结束了,网络线程还没获取到数据,此时jsontext当然为空
修改源码,将获取网络数据放入AsyncTask中,
class  MyAsycTask extends AsyncTask<String,Void,String>{@Overrideprotected void onPreExecute() {super.onPreExecute();System.out.print("异步线程开始");}@Overrideprotected void onPostExecute(String s) {super.onPostExecute(s);WeatherBean weatherBean = JSONUtil.getWeatherBean(s);country.setText(weatherBean.getCountry());humidity.setText(weatherBean.getHumidity() + "");pressure.setText(weatherBean.getPressure() + "");temperature.setText(weatherBean.getTemperature() + "");System.out.println("test2");}@Overrideprotected String doInBackground(String... params) {InputStream is =null;BufferedReader in = null;String jsonText="";URL url= null;try {url = new URL(params[0]);} catch (MalformedURLException e) {e.printStackTrace();}try {HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(10000 /* milliseconds */);conn.setConnectTimeout(15000 /* milliseconds */);conn.setRequestMethod("GET");conn.setDoInput(true);conn.connect();is = conn.getInputStream();in = new BufferedReader(new InputStreamReader(is));String line = "";while((line = in.readLine()) != null){jsonText += line;}} catch (IOException e) {e.printStackTrace();}finally{try {in.close();is.close();} catch (IOException e) {e.printStackTrace();}}return jsonText;}}
调试了两次之后,成功获取到数据
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息