当前位置:   article > 正文

Android studio 之天气预报(Webservice)_andriod studio天气预报

andriod studio天气预报

目录

引言:

1.该项目的实现效果

 2.activity_main.xml代码:

 3.MainActivity.java代码:

4.关于开启网络权限的方法:


引言:

因为本人在做这个天气预报的时候,遭遇了不少挫折,一直无法通过webservices去访问天气,后来看到返回语句有说是注册一个webservices的账号就行,但不知为何,我一直无法注册成功,明明在测试里头,没有填注册信息也是可以直接访问。再然后找到一个说是免费的一个getWeatherbyCityName,结果也一直不得其法。所以最后做出来这个项目后,决定将这个做好的项目发出来,与大家一起学习!一定要配置好网络权限哈!!!

1.该项目的实现效果

 2.activity_main.xml代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context=".MainActivity">
  8. <Button
  9. android:id="@+id/button"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:text="@string/b1"
  13. android:gravity="center"
  14. android:textSize="22dp"
  15. android:textColor="@color/black"
  16. android:backgroundTint="@color/hui"
  17. app:layout_constraintBottom_toBottomOf="parent"
  18. app:layout_constraintEnd_toEndOf="parent"
  19. app:layout_constraintHorizontal_bias="0.394"
  20. app:layout_constraintStart_toStartOf="parent"
  21. app:layout_constraintTop_toTopOf="parent"
  22. app:layout_constraintVertical_bias="0.124" />
  23. <Button
  24. android:id="@+id/button2"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:text="@string/b2"
  28. android:textColor="@color/black"
  29. android:gravity="center"
  30. android:textSize="22dp"
  31. android:backgroundTint="@color/hui"
  32. app:layout_constraintBottom_toBottomOf="parent"
  33. app:layout_constraintEnd_toEndOf="parent"
  34. app:layout_constraintHorizontal_bias="0.69"
  35. app:layout_constraintStart_toStartOf="parent"
  36. app:layout_constraintTop_toTopOf="parent"
  37. app:layout_constraintVertical_bias="0.124" />
  38. <EditText
  39. android:id="@+id/edit"
  40. android:layout_width="330dp"
  41. android:layout_height="500dp"
  42. android:ems="10"
  43. android:hint="Small text"
  44. android:textColorHint="@color/black"
  45. android:gravity="start|top"
  46. android:inputType="textMultiLine"
  47. app:layout_constraintBottom_toBottomOf="parent"
  48. app:layout_constraintEnd_toEndOf="parent"
  49. app:layout_constraintStart_toStartOf="parent"
  50. app:layout_constraintTop_toTopOf="parent"
  51. app:layout_constraintVertical_bias="1.0" />
  52. </androidx.constraintlayout.widget.ConstraintLayout>

 3.MainActivity.java代码:

  1. package com.example.weather;
  2. import android.os.AsyncTask;
  3. import android.os.Bundle;
  4. import android.os.Handler;
  5. import android.os.Message;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.EditText;
  10. import android.widget.TextView;
  11. import android.widget.Toast;
  12. import androidx.appcompat.app.AppCompatActivity;
  13. import org.ksoap2.SoapEnvelope;
  14. import org.ksoap2.serialization.SoapObject;
  15. import org.ksoap2.serialization.SoapSerializationEnvelope;
  16. import org.ksoap2.transport.HttpTransportSE;
  17. import org.xmlpull.v1.XmlPullParserException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.io.OutputStreamWriter;
  21. import java.net.URL;
  22. import java.net.URLConnection;
  23. import javax.xml.parsers.DocumentBuilder;
  24. import javax.xml.parsers.DocumentBuilderFactory;
  25. import org.w3c.dom.Document;
  26. import org.w3c.dom.Node;
  27. import org.w3c.dom.NodeList;
  28. import java.io.IOException;
  29. public class MainActivity extends AppCompatActivity {
  30. private Button b1;
  31. private Button b2;
  32. private TextView t1;
  33. private String result;
  34. private EditText e1;
  35. String a;
  36. @Override
  37. protected void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.activity_main);
  40. b1=findViewById(R.id.button);
  41. b2=findViewById(R.id.button2);
  42. e1=findViewById(R.id.edit);
  43. b1.setOnClickListener(new View.OnClickListener() {
  44. @Override
  45. public void onClick(View v) {
  46. a=b1.getText().toString().trim();
  47. //启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI
  48. QueryAddressTask queryAddressTask = new QueryAddressTask();
  49. //启动后台任务
  50. queryAddressTask.execute();
  51. }
  52. });
  53. b2.setOnClickListener(new View.OnClickListener() {
  54. @Override
  55. public void onClick(View v) {
  56. a=b2.getText().toString().trim();
  57. //启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI
  58. QueryAddressTask queryAddressTask = new QueryAddressTask();
  59. //启动后台任务
  60. queryAddressTask.execute();
  61. }
  62. });
  63. }
  64. public static String getWeather(String city) {
  65. try {
  66. Document doc;
  67. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  68. dbf.setNamespaceAware(true);
  69. DocumentBuilder db = dbf.newDocumentBuilder();
  70. //输入要查询的地名
  71. InputStream is = getSoapInputStream(city);
  72. doc = db.parse(is);
  73. NodeList nl = doc.getElementsByTagName("string");
  74. StringBuffer sb = new StringBuffer();
  75. for (int count = 0; count < nl.getLength(); count++) {
  76. Node n = nl.item(count);
  77. if(n.getFirstChild().getNodeValue().equals("查询结果为空!")) {
  78. sb = new StringBuffer("") ;
  79. break ;
  80. }
  81. sb.append(n.getFirstChild().getNodeValue() + "\n");
  82. }
  83. is.close();
  84. return sb.toString();
  85. } catch (Exception e) {
  86. e.printStackTrace();
  87. return null;
  88. }
  89. }
  90. private static InputStream getSoapInputStream(String city) throws Exception {
  91. try {
  92. //执行网页查询操作啦!
  93. String soap = getSoapRequest(city);
  94. if (soap == null) {
  95. return null;
  96. }
  97. URL url = new URL(
  98. "http://www.webxml.com.cn/WebServices/WeatherWS.asmx");
  99. URLConnection conn = url.openConnection();
  100. conn.setUseCaches(false);
  101. conn.setDoInput(true);
  102. conn.setDoOutput(true);
  103. //差点被坑了!!!
  104. // conn.setRequestProperty("Content-Length", Integer.toString(soap
  105. // .length()));
  106. conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
  107. conn.setRequestProperty("SOAPAction",
  108. "http://WebXml.com.cn/getWeather");
  109. OutputStream os = conn.getOutputStream();
  110. OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
  111. osw.write(soap);
  112. osw.flush();
  113. osw.close();
  114. InputStream is = conn.getInputStream();
  115. return is;
  116. } catch (Exception e) {
  117. e.printStackTrace();
  118. return null;
  119. }
  120. }
  121. private static String getSoapRequest(String city) {
  122. StringBuilder sb = new StringBuilder();
  123. sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  124. + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
  125. + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
  126. + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
  127. + "<soap:Body> <getWeather xmlns=\"http://WebXml.com.cn/\">"
  128. + "<theCityCode>" + city
  129. + "</theCityCode> </getWeather>"
  130. + "</soap:Body></soap:Envelope>");
  131. return sb.toString();
  132. }
  133. String result1;
  134. //执行这些还是得在异步线程里呀,小心翻车
  135. class QueryAddressTask extends AsyncTask<Void,Integer,Boolean>{
  136. @Override
  137. protected Boolean doInBackground(Void... voids) {
  138. result1 = getWeather(a); //在子线程中请求webservice
  139. return null;
  140. }
  141. @Override
  142. protected void onPostExecute(Boolean aBoolean) {
  143. StringBuilder builder = new StringBuilder();
  144. e1.setText(result1);
  145. //Toast.makeText(MainActivity.this, result1, Toast.LENGTH_SHORT).show();
  146. }
  147. }
  148. }

4.关于开启网络权限的方法:

具体可以参考一下我上一篇文章和所用到的api:​​​​​​(2条消息) Android Studio之号码归属地查询(Webservice)_芒心008的博客-CSDN博客

因为api不同开启网络权限的方法有些许不同,如果一直不得其法,建议换个api再运行,有不懂的欢迎留言!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/468025
推荐阅读
相关标签
  

闽ICP备14008679号