Android-okhttp-get请求-简单爬虫技术-获取天气预报信息

一、实现效果截图:

​​​​​​​

二、代码

1、导入依赖

首先找到Okhttp的网址:https://github.com/square/okhttp

找到依赖

复制到自己建立的Android工程中的 ->Android工程结构下

第二个build.gradle中并点击加载

添加网络授权

以上条件满足了就设置界面

界面UI代码activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="okhttp" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="统计抓去的数据个数" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="显示抓去的数据"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>

在MainActivity中写代码

package com.guozijun.okhttp;

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

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    //okhttp按钮
    Button button;
    //显示字符个数
    TextView textView;
    //显示抓去的内容
    TextView textView_01;

    //定义okhttp客户端
    private  OkHttpClient okHttpClient = new OkHttpClient();

    //定义
    Handler hander = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //判断消息请求有错误的消息
           if (msg.what == 0x01){
              //显示消息
               textView.setText(msg.obj.toString());
           }
           //判断请求正确的消息
            if (msg.what == 0x02){

                //计算消息长度
                long str = (long) msg.obj.toString().length();

               //消息个数
                textView_01.setText("字符个数:"+String.valueOf(str));

               //想要的信息
                textView.setText("北京天气预报:"+msg.obj.toString());
            }

        }
    };

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

        //关联定义按钮
        button = findViewById(R.id.button);
        //关联定义文本框
        textView = findViewById(R.id.textView);
        //关联定义文本框
        textView_01 = findViewById(R.id.textView2);

       //按钮网络请求事件
        button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {

               //创建请求构造器
               Request.Builder builder = new Request.Builder();

               //添加URL
               builder.url("https://tianqi.moji.com/today/china/beijing/beijing
");

               //创建请求
               Request request = builder.build();

               //定义call对象
               Call call = okHttpClient.newCall(request);

               //定义消息对象
               Message message = new Message();

               //启动异步请求
               call.enqueue(new Callback() {

                   //网络请求失败事件
                   @Override
                   public void onFailure(@NonNull Call call, @NonNull IOException e) {

                       //定义消息what属性
                       message.what = 0x01;

                       //获取请求失败异常消息
                       message.obj = "请求失败"+e.getMessage();

                       //线程间传递消息
                       hander.sendMessage(message);

                       
                   }

                  //网络成功请求相应事件
                   @Override
                   public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                       //定义消息what属性
                       message.what = 0x02;

                       //请求获取想要的消息,利用字符截取想要的信息,从递
                       message.obj = response.body().string().substring(193,281);

                       //线程间传递消息
                       hander.sendMessage(message);


                   }
               });

           }
       });

    }
}

附录(下面网址中的天气信息仅供参考学习使用,严禁商用)

天气信息原地址:https://tianqi.moji.com/today/china/beijing/beijing

输入浏览器查看源码

​​​​​​​

截取画红线部分的信息,把画红线的部分的开始字符的位置到结束的位置计算出来,可以把字符串放到world中来计算字符个数,然后用substring()方法截取,慢慢调试,注意okhttp,在手机上实测APP对于http://协议不能请求成功,要换成http手://协议请求。

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值