本文档为个人博客文档系统的备份版本、作者:小游、作者博客:点击访问
这里我使用第三方库:https://github.com/square/okhttp/
引入方法:implementation("com.squareup.okhttp3:okhttp:4.4.0")
但是引入报错。。。

emm,研究了半天,国外找了好多都无法解决。
刚开始以为是项目的问题在最后才发现是我改了一下项目的文件。。。

太难了我,这个问题困扰了整整一上午。。。
最简单的使用方法:
private void getDataAsync() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){//回调的方法执行在子线程。
Log.d("kwwl","获取数据成功了");
Log.d("kwwl","response.code()=="+response.code());
Log.d("kwwl","response.body().string()=="+response.body().string());
}
}
});
}
上面这个是异步调用方法。
下面看一下同步调用
OkHttpClient client =new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
try {
Response response = call.execute();
Log.d("kwwl","获取数据成功了");
Log.d("kwwl","response.code()=="+response.code());
Log.d("kwwl","response.body().string()=="+ Objects.requireNonNull(response.body()).string());
} catch (IOException e) {
e.printStackTrace();
}
return "";
注意如果报错 android.os.NetworkOnMainThreadException
那是因为http请求不能在主线程中执行。我们需要在子线程中去执行这个请求。
发送post请求
参考链接https://blog.csdn.net/qingfeng812/article/details/52130861
OkHttpClient client=new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
Request request=new Request.Builder()
.url(url)
.post(formBody)
.build();
try{
Response response=client.newCall(request).execute();
if(response.isSuccessful()){
String data= Objects.requireNonNull(response.body()).string();
//使用正则来判断并获取数据
Matcher type= P1.matcher(data);
Matcher result= P2 .matcher(data);
if(type.find() && Objects.equals(type.group(1), ok)){
if(result.find()){
return result.group(1);
}
}
}
return null;
}catch (Exception e){
Log.e(Variable.TAG, Objects.requireNonNull(e.getMessage()));
return null;
}
本文档介绍了在Android中如何使用OkHttp库发送HTTP请求,包括同步和异步调用的方法。在尝试引入库时遇到问题,最终发现是由于项目文件改动导致的错误。并提醒开发者HTTP请求不能在主线程执行,需要在子线程中进行。
123

被折叠的 条评论
为什么被折叠?



