Android Studio 使用GET方式获取天气

 手机登录校园网极其费劲,时常打不开校园网的登录页面,打开了也存不住账号密码

为了不要每次都输一遍,打算做个手动登录校园网的APP

经过抓包发现校园网只需通过get请求发送ip,账号和密码即可登录成功,就在某篇文章里找到了这个GET获取天气的方法,改过许多遍,在我目前的JDK8环境下能跑起来

注意,Android中访问网络需要开启子线程来完成

package com.example.myapplication;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

public class MainActivity extends AppCompatActivity {
    private TextView tvContent;
    private Handler mHandler = new Handler(Looper.myLooper()){

    public void handleMessage(@NonNull Message msg){
        tvContent = findViewById(R.id.tv_content);
        super.handleMessage(msg);

        if(msg.what==0){
            String strData = (String)msg.obj;
            tvContent.setText(strData);
            Toast.makeText(MainActivity.this,"主线程收到网络消息啦!",Toast.LENGTH_SHORT).show();
        }
    }
};

    private String getStringFormNet(){
        //从网络上获取字符串
        return NetUtil.getWeatherOfCity("赣州");
    }

    public void start(View view){
        //做一个耗时任务
        new Thread(new Runnable(){
            @Override
            public void run(){
                String stringFormNet = getStringFormNet();

                //使用handler来发送消息
                Message message = new Message();
                message.what = 0;//用于区分是谁发的消息
                message.obj = stringFormNet;
                mHandler.sendMessage(message);

            }
        }).start();
        Toast.makeText(MainActivity.this,"开启子线程请求网络!",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        start(findViewById(R.id.tv_content));//tvcontent是一个textview
        Log.d("success", "成功启动 ");

        setContentView(R.layout.activity_main);






}

MainActivity.java

使用geteather of city函数完成对城市的传参,并且拼接get请求的url传入Netutil函数进行http请求

package com.example.myapplication;

import android.util.Log;

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.ProtocolException;
import java.net.URL;

public class NetUtil{
    public static String BASE_URL="https://v0.yiketianqi.com/free/day";
    public static String APP_ID="14846972";
    public static String APP_SECRET="Guya4Gz2";

    public static String doGet(String url){
        BufferedReader reader = null;
        String bookHSONString = null;
        String bookJSONString;
        HttpURLConnection httpURLConnection = null;
        try{
            String uc = null;
            //1.HttpURLConnection建立连接

            URL requestUrl = new URL(url);
            httpURLConnection = (HttpURLConnection)requestUrl.openConnection();//打开连接
            httpURLConnection.setRequestMethod("GET");//两种方法GET/POST
            httpURLConnection.setConnectTimeout(5000);//设置超时连接时间
            httpURLConnection.connect();

            //2.InputStream获取二进制流
            InputStream inputstream = httpURLConnection.getInputStream();

            //3.InputStreamReader将二进制流进行包装成BufferedReader
            reader = new BufferedReader(new InputStreamReader(inputstream));

            //4.从BufferedReader中读取String字符串,用StringBulider接收
            StringBuilder builder = new StringBuilder();


            String line;
            while((line=reader.readLine())!=null){
                builder.append(line);
                builder.append("\n");
            }

            if(builder.length()==0)
            {
                return null;
            }

            //5.StringBulider将字符串进行拼接
            bookJSONString = builder.toString();

        }

        catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        finally {
            // 关闭连接
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bookJSONString;
    }

    public static String getWeatherOfCity(String city){
        //拼接处get请求的url
        String weatherUrl = BASE_URL+"?"+"appid="+APP_ID+"&"+"appsecret="+APP_SECRET+"&"+"city="+city;
        //打印上面的url
        Log.d("fan","-----weatherUrl----"+weatherUrl);

        //调用上文所写的doGet方法,传参
        String weatherResult = doGet(weatherUrl);
        return decodeUnicode(weatherResult);
    }

    //解码Unicode,将其转化为我们认识的汉字
    public static String decodeUnicode(String unicodeStr) {
        if (unicodeStr == null) {
            return null;
        }
        StringBuffer retBuf = new StringBuffer();
        int maxLoop = unicodeStr.length();
        for (int i = 0; i < maxLoop; i++) {
            if (unicodeStr.charAt(i) == '\\') {
                if ((i < maxLoop - 5) && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr.charAt(i + 1) == 'U')))
                    try {
                        retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));
                        i += 5;
                    } catch (NumberFormatException localNumberFormatException) {
                        retBuf.append(unicodeStr.charAt(i));
                    }
                else
                    retBuf.append(unicodeStr.charAt(i));
            } else {
                retBuf.append(unicodeStr.charAt(i));
            }
        }
        return retBuf.toString();
    }


}




NetUtil.java   运行子线程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Android Studio和心知天气API创建天气预报应用的步骤: 1. 在Android Studio中创建一个新的项目。 2. 在项目的build.gradle文件中添加以下依赖项: ```groovy implementation 'com.android.volley:volley:1.2.0' implementation 'com.google.code.gson:gson:2.8.7' ``` 3. 在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 4. 创建一个新的Java类,命名为Weather.java,用于存储天气信息的数据模型。 ```java public class Weather { private String city; private String temperature; private String weather; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } } ``` 5. 创建一个新的Java类,命名为WeatherRequest.java,用于发送天气请求并解析JSON响应。 ```java public class WeatherRequest { private static final String API_KEY = "YOUR_API_KEY"; private static final String BASE_URL = "https://api.seniverse.com/v3/weather/now.json"; public interface WeatherCallback { void onSuccess(Weather weather); void onError(String message); } public static void getWeather(String city, WeatherCallback callback) { String url = BASE_URL + "?key=" + API_KEY + "&location=" + city; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, response -> { try { JSONObject result = response.getJSONObject("results").getJSONArray("now").getJSONObject(0); Weather weather = new Weather(); weather.setCity(result.getString("location")); weather.setTemperature(result.getString("temperature")); weather.setWeather(result.getString("text")); callback.onSuccess(weather); } catch (JSONException e) { callback.onError("Failed to parse JSON response"); } }, error -> callback.onError("Failed to make weather request")); RequestQueue queue = Volley.newRequestQueue(context); queue.add(request); } } ``` 6. 在MainActivity.java中,添加以下代码来获取天气信息并更新UI: ```java public class MainActivity extends AppCompatActivity { private TextView cityTextView; private TextView temperatureTextView; private TextView weatherTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cityTextView = findViewById(R.id.cityTextView); temperatureTextView = findViewById(R.id.temperatureTextView); weatherTextView = findViewById(R.id.weatherTextView); WeatherRequest.getWeather("YOUR_CITY", new WeatherRequest.WeatherCallback() { @Override public void onSuccess(Weather weather) { runOnUiThread(() -> { cityTextView.setText(weather.getCity()); temperatureTextView.setText(weather.getTemperature()); weatherTextView.setText(weather.getWeather()); }); } @Override public void onError(String message) { runOnUiThread(() -> Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show()); } }); } } ``` 请注意,将"YOUR_API_KEY"替换为您在心知天气网站上获取的API密钥,并将"YOUR_CITY"替换为您想要获取天气信息的城市。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值