一、实现效果截图:
二、代码
1、导入依赖
首先找到Okhttp的网址:https://github.com/square/okhttp
找到依赖
复制到自己建立的Android工程中的 ->Android工程结构下
第二个build.gradle中并点击加载
添加网络授权
以上条件满足了就设置界面
界面UI代码activity_main.xml
在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("http://www.weather.com.cn/weather1d/101010100.shtml");
//创建请求
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(27498,27509);
//线程间传递消息
hander.sendMessage(message);
}
});
}
});
}
}
附录(下面网址中的天气信息仅供参考学习使用,严禁商用)
天气信息原地址:http://www.weather.com.cn/weather1d/101010100.shtml
输入浏览器查看源码
截取画红线部分的信息,把画红线的部分的开始字符的位置到结束的位置计算出来,可以把字符串放到world中来计算字符个数,然后用substring()方法截取。



