OkHttp 配置
OkHttp 配置
1、下载依赖
在build.gradle的文件里面添加依赖
implementation("com.squareup.okhttp3:okhttp:3.10.0")
2、在清单文件中做网络的配置
<!-- 是为了可以访问网络 -->
<uses-permission android:name="android.permission.INTERNET" />
3、在xml文件夹下面创建network_security_config.xml
写入一下文件
<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 禁用流量明文检查-->
<base-config cleartextTrafficPermitted= "true"/>
</network-security-config>
4、在清单文件中引入xml文件
android:networkSecurityConfig="@xml/network_security_config"
5、 在activity或者fragment中写入OkHttp传输的代码
private void ViolationInfo(){
// 第一步创建
OkHttpClient client = new OkHttpClient.Builder()
.build();
//第二步创建Rquest
Request request = new Request.Builder()
.url(AppConfig.BASE_URl + "/violation-info/selectAll") //访问的url地址
.addHeader("contentType", "application/json;charset=UTF-8")
// .post(requestBodyJson)
.build();
//第三步创建call回调对象
Call call = client.newCall(request);
//第四步发起请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("1111", "onResponse: "+7676767);
// Toast.makeText(getActivity(), "onFailure",
// Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String result = response.body().string();
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(result);
for(int i = 0 ; i < jsonArray.length();i++){
values.put("violationId", (int) jsonArray.getJSONObject(i).get("violationId"));
values.put("violationName",(String) jsonArray.getJSONObject(i).get("violationName"));
values.put("violationAction",(String) jsonArray.getJSONObject(i).get("violationAction"));
values.put("violationNumber", (String) jsonArray.getJSONObject(i).get("violationNumber"));
db.insert("violationInfo_1",null, values);
values.clear();
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
//测试
// Toast.makeText(ManageViolation.this, result,
// Toast.LENGTH_SHORT).show();
}
});
}
});
}
上述onResponse()中写入想要接收数据的代码
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 胡萝卜!