okHttp的使用
1、首先添加依赖build.gradle文件中添加
plugins {
id 'com.android.application'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.myapplication"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
//这里也需要添加,否则添加依赖时会报错
packagingOptions{
exclude 'META-INF/DEPENDENCIES'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.firebase:firebase-crashlytics-buildtools:2.5.2'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
//okhttp 添加依赖
implementation 'com.squareup.okhttp3:okhttp:4.4.0'
}
2、添加httpulit.java类 这里只写了同步的。异步的可以另外写
public class HttpUtils { private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static OkHttpClient client = new OkHttpClient(); public static Response post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response; } public static Response get(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response; } }
3、业务事件里面添加,同步的里面需要另起一个线程
new Thread(){ @Override public void run() { Response response = null; try { response = get("https://ip.help.bj.cn/?ip=202.98.0.68"); String data = new String(response.body().bytes(),"GB2312"); Log.i(TAG, "run: "+data); //parseJsonWith(data); } catch (IOException e) { //e.printStackTrace(); Toast.makeText(getApplicationContext(),"网络请求错误",Toast.LENGTH_LONG).show(); } } }.start();