注:此方法只对初学者应急使用,应该有不少基础不扎实又被推上战场的家伙。便于理解。看不懂要回去看看json数据解析,数组和集合的章节,最后随便找一下okhttp的基础教程就没问题了
get异步请求
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("网址")
.build();
//异步请求
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//数据处理
String string = response.body().string();
Log.e("输出:",":"+string);
Gson gson = new Gson();
//Gsonjx是我自己写的数据解析类,里面是网络获取的数组的里面的数据类型与名称
Gsonjx gsonjx = gson.fromJson(string, Gsonjx.class);
List<Object> rows = gsonjx.getRows();
JSONArray jsonArray = new JSONArray(rows);
for (int i = 0;i<jsonArray.length();i++){
try {
JSONObject o = (JSONObject) jsonArray.get(i);
String advImg = o.getString("advImg");
//存储数据,List<String> list = new ArrayList();
list.add("http://124.93.196.45:10001"+advImg);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
post异步请求
//从页面上获取到的数据
String ss1 = editText1.getText().toString().trim();
String ss2 = editText2.getText().toString().trim();
OkHttpClient okHttpClient = new OkHttpClient();
//携带的参数类型
MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
//携带参数
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username",ss1);
jsonObject.put("password",ss2);
} catch (JSONException e) {
e.printStackTrace();
}
//装进RequestBody
RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(),mediaType);
Request request = new Request.Builder()
.post(requestBody)
.url("地址")
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String string = response.body().string();
Log.e("输出:",":"+string);
Gson gson = new Gson();
Gsonjx gsonjx = gson.fromJson(string, Gsonjx.class);
String code = gsonjx.getCode();
if (code.equals("200")){
String token = gsonjx.getToken();
//不用管这,这是个轻量化的数据存储
SharedPreferences.Editor sharedPreferences = getSharedPreferences("wenjian",0).edit();
sharedPreferences.putString("Token",token);
sharedPreferences.commit();
Intent intent = new Intent(MainActivity.this,DbdhlActivity.class);
startActivity(intent);
}else {
}
}
});