网络权限
引入okhttp包:
implementation 'com.squareup.okhttp3:okhttp:3.14.4'
在app module下的build.gradle文件中配置java8,否则会报错。
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
...
}
buildTypes {
...
}
// 增加java8的配置
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
MainActivity代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
String url = "https://publicobject.com/helloworld.txt";
//初始化okhttp客户端
OkHttpClient client = new OkHttpClient();
//创建请求体
Request request = new Request.Builder().url(url).get().build();
//执行请求
Response response = null;
try {
response = client.newCall(request).execute();
//获取服务器响应数据
if (response.isSuccessful()) {
String result = response.body().string();
Log.e("xxx", result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}