安卓--请求接口
程序员文章站
2022-06-13 21:10:59
...
1.引入gradle
//请求
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.10.0'
implementation 'com.google.code.gson:gson:2.8.5'
2.封装请求类
package com.example.httpapplication.api;
import static android.content.Context.MODE_PRIVATE;
import android.content.Context;
import android.content.SharedPreferences;
import com.example.httpapplication.Utils.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
*单例模式
**/
public class Api {
private static String reequestUrl;
private static OkHttpClient okHttpClient;
private static HashMap<String,Object> mparams;
public static Api api=new Api();
public Api(){};
public static Api config(String url, HashMap<String,Object> params){
//1.创建OkHttpClient
okHttpClient=new OkHttpClient.Builder().build();
reequestUrl=AppConfig.BASE_URL+url;
mparams=params;
return api;
}
// 封装的POST请求
public void postRequest(TtitCallback callback){
JSONObject jsonObject=new JSONObject(mparams);
String jsonstr=jsonObject.toString();
String Content_Type="application/json;charset=utf-8";
RequestBody requestBodyJson=RequestBody.create(MediaType.parse(Content_Type),jsonstr);
// 2.创建request
Request request=new Request.Builder()
.url(reequestUrl)
.addHeader("contentType", "application/json;charset=UTF-8")
.post(requestBodyJson)
.build();
// 3.创建call回调对象
final Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
callback.onFailure(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result=response.body().string();
callback.onSuccess(result);
}
});
}
// 封装的GET请求
public void getRequest(Context context, final TtitCallback callback) {
SharedPreferences sp = context.getSharedPreferences("sp_ttit", MODE_PRIVATE);
String token = sp.getString("token", "");
String url = getAppendUrl(reequestUrl, mparams);
Request request = new Request.Builder()
.url(url)
.addHeader("token", token)
.get()
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String result = response.body().string();
try {
JSONObject jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
callback.onSuccess(result);
}
});
}
private static String getAppendUrl(String reequestUrl, HashMap<String, Object> mparams) {
if(mparams!=null&&!mparams.isEmpty()){
StringBuilder stringBuilder=new StringBuilder();
Iterator<Map.Entry<String,Object>> interactor=mparams.entrySet().iterator();
while (interactor.hasNext()){
Map.Entry<String,Object> entry=interactor.next();
if(StringUtils.isEmpty(stringBuilder.toString())){
stringBuilder.append("?");
}else{
stringBuilder.append("&");
}
stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
}
reequestUrl+=stringBuilder.toString();
}
return reequestUrl;
}
}
3.存放接口名
/**
*
**/
public class AppConfig {
public static final String BASE_URL="http://192.168.0.104:8888/api";
public static final String login="/login";
public static final String register="/register";
public static final String getVideoType="/getVideoType";
public static final String getVideoList="/getVideoList";
public static final String getiNews="/getiNews";
}
4.请求结果回调函数
/**
*
**/
public interface TtitCallback {
void onSuccess(String res);
void onFailure(Exception e);
}
5.返回结果实体类
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
*
**/
public class ResponseApi implements Serializable {
private int code;
private String mag;
private List<Map<String,Object>> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMag() {
return mag;
}
public void setMag(String mag) {
this.mag = mag;
}
public List<Map<String,Object>> getData() {
return data;
}
public void setData(List<Map<String,Object>> data1) {
this.data = data1;
}
@Override
public String toString() {
return "VideoListResponse{" +
"code=" + code +
", mag='" + mag + '\'' +
", data1=" + data +
'}';
}
}
6.使用请求结果界面
package com.example.httpapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.example.httpapplication.api.Api;
import com.example.httpapplication.api.AppConfig;
import com.example.httpapplication.api.TtitCallback;
import com.example.httpapplication.entity.ResponseApi;
import com.example.httpapplication.entity.VideoInfo;
import com.example.httpapplication.entity.VideoInfo;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private String TAG="首页";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getVideoList();
}
private Handler mhandler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
//放在这里面就在UI朱线程里面执行
switch (msg.what){
case 0:
// 渲染数据
// videoAdapter.setDatas(list);
// videoAdapter.notifyDataSetChanged();//通知recyview刷新页面
break;
case 1:
break;
}
}
};
private void getVideoList(){
//参数
HashMap<String,Object> params=new HashMap<>();
params.put("categoryId",1);//视频分类id
//附带参数
HashMap<String,Object> fudaimap=new HashMap<>();
fudaimap.put("start",0);
fudaimap.put("end",5);
params.put("params",fudaimap);
//请求视频列表
Api.config(AppConfig.getVideoList,params).postRequest(new TtitCallback() {
@Override
public void onSuccess(String res) {
Log.d(TAG, res);
ResponseApi responseApi=new Gson().fromJson(res,ResponseApi.class);
if(responseApi!=null&&responseApi.getCode()==0){
List<Map<String,Object>> listVideos=responseApi.getData();
for (int a=0;a<listVideos.size();a++){
Map<String,Object> hashmap= listVideos.get(a);
Log.d(TAG, hashmap.get("author").toString());
}
mhandler.sendEmptyMessage(0);//通知去渲染界面
}
}
@Override
public void onFailure(Exception e) {
}
});
}
}
上一篇: 万能转接头之适配器模式
下一篇: 2019最新推荐的10个自助建站平台
推荐阅读
-
谷歌出手强推USB-PD快充:不支持的安卓手机或无缘GMS服务
-
谷歌要求安卓手机厂商最新机型支持USB PD快充标准
-
安卓品牌换机留存率TOP 10出炉 华为Mate系列成第一
-
这就是微软折叠屏手机Surface Duo!采用谷歌深度定制安卓系统
-
安卓11加入全新手势:双击手机背部激活特定功能
-
小米9 Pro定制超大号横向线性马达:可能是安卓手机中最好的
-
安卓Q新功能了解下:所有APP播视频无需联网可生成字幕
-
安卓8.0及以上机型开放华为云电脑:手机秒变Windows电脑
-
发布四年 安卓6.0升级到安卓8.0 三星Galaxy S7/edge停止系统更新
-
被锤打7年之后 安卓这个功能终于追上了iOS