美文网首页我爱编程
在Android Studio平台实现访问web service

在Android Studio平台实现访问web service

作者: 卤小贝 | 来源:发表于2018-05-27 21:01 被阅读0次

    简易的天气预报APP

    项目链接(https://github.com/lubeiling/getWeather-Information-based-Android)

    效果图如下,需要输入汉字,AVD可修改输入配置。

    1、系统配置:安装好Android Studio,配置好SDK和AVD;

    2、开始创建项目

    (1)新建Audroid项目


    (2)访问互联网, 首先需要设置好相应权限

            在app文件夹->mainifests文件夹->AndroidManifest.xml文件中添加:

                                <uses-permission android:name="android.permission.INTERNET" />


    (3)在MainActivity.java中获取网络数据用到HttpURLConnection的GET方法,并在子线程中访问网络(因为访问网络比较耗时,所以放在子线程中执行;通过消息返回的数据传回页面(更新UI界面)),这里用到的是Handler线程机制:

    页面代码(activity_main.xml)如下:

    <?xml version="1.0" encoding="utf-8"?>

    <android.support.constraint.ConstrainLayout        xmlns:android="http://schemas.android.com/apk/res/android"

            xmlns:app="http://schemas.android.com/apk/res-auto"

            xmlns:tools="http://schemas.android.com/tools"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            tools:context=".MainActivity">

    <EditText

              android:id="@+id/cityName"

              android:layout_width="match_parent"

              android:layout_height="wrap_content"

              android:hint="请输入城市名称" />

    <Button

            android:id="@+id/button2"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="查询天气"

            android:onClick="button_click_2"

            app:layout_constraintTop_toBottomOf="@+id/cityName"/>

    <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:id="@+id/resultText"

            app:layout_constraintTop_toBottomOf="@+id/button2" />

    </android.support.constraint.ConstrainLayout>


    MainActivity.java代码如下:

    package com.example.a2017.homenwork_first;

    import android.os.Bundle;

    import android.os.Handler;

    import android.os.Message;

    import android.support.v7.app.AppCompatActivity;

    import android.util.Log;

    import android.view.View;

    import android.widget.EditText;

    import android.widget.TextView;

    import android.widget.Toast;

    import org.json.JSONException;

    import org.json.JSONObject;

    import java.io.BufferedReader;

    import java.io.IOException;

    import java.io.InputStream;

    import java.io.InputStreamReader;

    import java.net.HttpURLConnection;

    import java.net.MalformedURLException;

    import java.net.URL;

    public class MainActivityextends AppCompatActivity {

        //更新UI

        private Handlerhandler =new Handler() {

        @Override

            public void handleMessage(Message msg) {

            // 处理消息时需要知道是成功的消息还是失败的消息

              TextView resultText = (TextView) findViewById(R.id.resultText);

                switch (msg.what){

                case 0:

                    resultText.setText(msg.obj.toString());

                break;

            }

        }

    };

    @Override

     protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        }

    //按钮触发事件

        public void button_click_2(View view){

         //子线程

            Thread t =new Thread(){

                @Override

                public void run() {

                    HttpURLConnection connection =null;

                            try {

                                    EditText ed = (EditText)findViewById(R.id.cityName);

                                   //在测试时,编辑框中需要填写汉字

                                    String city = java.net.URLEncoder.encode(ed.getText().toString(),"utf-8");

                                 //如果AVD模拟器不能输入汉字时,需要用下面这行代码替换上一行

                                    //String city = java.net.URLEncoder.encode("广州", "utf-8");

                                     URL url =new URL("http://wthrcdn.etouch.cn/weather_mini?city="+city);

                                    connection = (HttpURLConnection) url.openConnection();

                                   connection.setRequestMethod("GET");

                                   connection.setConnectTimeout(5000);

                                   connection.setReadTimeout(5000);

                                   InputStream in = connection.getInputStream();

                                   BufferedReader reader =new BufferedReader(new InputStreamReader(in));

                                   StringBuilder response =new StringBuilder();

                                   String line;

                                   while ((line = reader.readLine()) !=null) {

                                   response.append(line);

                                   }

                                   //在日志中输出网络返回的数据

                                   Log.i("TAG", response.toString());

                                   //将获得到的数据进行处理,得到我们需要的格式

                                   String res =new String(response);

                             try {

                                   JSONObject jsonObject =new JSONObject(res);

                                   JSONObject root = jsonObject.getJSONObject("data");

                                   String log ="";

                                   log = log+"城市:"+root.getString("city")+"\n"+"PM2.5:"+root.getString("aqi")+"\n"+"\n";

                                   JSONObject yes = (JSONObject)root.getJSONObject("yesterday");

                                   log = log + yes.getString("date") +"\t"+yes.getString("high")+"~"+

                                   yes.getString("low")+"\t"+

                                   yes.getString("type")+"\t"+

                                   yes.getString("fx")+"\n"+"\n"+"\n";

                                   for (int i =0;i<4;i++){

                                   JSONObject arr = (JSONObject) root.getJSONArray("forecast").get(i);

                                   log = log +

                                   arr.getString("date")+"\t"+

                                   arr.getString("high")+"~"+

                                   arr.getString("low")+"\t"+

                                   arr.getString("type")+"\t"+

                                   arr.getString("fengxiang")+"\n"+"\n"+"\n";

                                   }

                                   //将消息传回主线程

                                   Message message =new Message();

                                   message.what =0;

                                   message.obj = log;

                                   handler.sendMessage(message);

                                   }

                                   catch (JSONException e) {

                                   e.printStackTrace();

                                   }

                           }catch (MalformedURLException e) {

                                   e.printStackTrace();

                            }catch (IOException e) {

                                   e.printStackTrace();

                          }

                    }

            };

            t.start();//开始线程

    }

    }

    相关文章

      网友评论

        本文标题:在Android Studio平台实现访问web service

        本文链接:https://www.haomeiwen.com/subject/xcvvjftx.html