导入第三方jar包
implementation 'com.alibaba:fastjson:1.2.49' implementation 'com.alibaba:fastjson:1.1.70.android'
创建Http类
public class HttpConnection { public static String getHttpRequest(String urlString){ URL url; InputStream in = null; HttpURLConnection conn = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setDoInput(true); conn.connect(); if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){ in = conn.getInputStream(); int len =0; byte[] buffer = new byte[1024]; while((len= in.read(buffer))!=-1){ out.write(buffer, 0, len); } return out.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(in!=null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if(conn!=null){ conn.disconnect(); } if(out!=null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } return "kong"; } }
天气部分的xml
界面上关于天气的代码
private TextView tianqi; private TextView weather_text; private TextView air_text; private ImageView pic_7;
air_text=findViewById(R.id.air_text); tianqi=findViewById(R.id.textView); pic_7=findViewById(R.id.pic_7); weather_text = (TextView) findViewById(R.id.wether_text); two(); showDateInfo();
private void weather() { new Thread( ){ String a; String b; @Override public void run(){ a= HttpConnection.getHttpRequest("https://devapi.qweather.com/v7/weather/now?location=101044000&key=你申请的key"); b= HttpConnection.getHttpRequest("https://devapi.qweather.com/v7/air/now?location=101044000&key=你申请的key"); runOnUiThread(new Runnable( ) { @Override public void run() { JSonObject jsonObject = JSON.parseObject(a); JSonObject jsonObject1 = JSON.parseObject(b); tianqi.setText((String) jsonObject.getJSONObject("now").get("text")); air_text.setText(" 空气质量"+(String) jsonObject1.getJSONObject("now").get("aqi")); weather_text.setText((String) jsonObject.getJSONObject("now").get("temp")+" ℃"); } }); } }.start(); }
key可以去和风天气申请
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)