赞
踩
android端如何发起请求调用后端数据接口,达到交互的效果。
注:有时候我们需要和后台有会话的时候,需要携带cookie信息,这个时候就需要getCookie方法来携带cookie信息了,这个时候就需要在登录的时候提前保存到本地,这个我们在下一篇会有详细描述。
1:首先我们需要在build.gradle中导入相关okhttp的依赖
- implementation 'com.squareup.okhttp3:okhttp:3.10.0' //okhttp
- implementation 'com.alibaba:fastjson:1.2.56' //阿里json处理
2:接下来就可以使用okhttp来调用了,代码我这边简单封装了一下,内容如下:
(1).这个是请求的工具类
- package com.zjxf.utils;
-
- import android.content.Context;
-
- import com.alibaba.fastjson.JSONObject;
- import com.zjxf.cache.CacheKeys;
- import com.zjxf.common.SysConst;
-
- import io.netty.util.internal.StringUtil;
- import okhttp3.CacheControl;
- import okhttp3.Callback;
- import okhttp3.MediaType;
- import okhttp3.OkHttpClient;
- import okhttp3.Request;
- import okhttp3.RequestBody;
-
- /**
- * created with IntelliJ IDEA
- *
- * @author: create by limu
- * Date: 2019/11/12
- * Time:9:39
- */
- public class RequestUtils {
-
- public static final MediaType FORM_CONTENT_TYPE = MediaType.parse("application/json;charset=utf-8");
-
- private static final byte[] LOCKER = new byte[0];
-
- private static RequestUtils mInstance;
-
- /**
- * post请求不传递参数
- *
- * @param url 请求地址
- * @param callback 执行函数
- */
- public void postEmpty(Context context, String url, final Callback callback) {
- OkHttpClient client = new OkHttpClient();
- Request request = new Request.Builder()
- .url(splicingUrl(url)).post(okhttp3.internal.Util.EMPTY_REQUEST)
- .addHeader("Cookie", getCookie(context))
- .cacheControl(CacheControl.FORCE_NETWORK)
- .build();
- client.newCall(request).enqueue(callback);
- }
-
- /**
- * get请求不传递参数
- *
- * @param url 请求地址
- * @param callback 执行函数
- */
- public void getEmpty(Context context, String url, final Callback callback) {
- OkHttpClient client = new OkHttpClient();
- Request request = new Request.Builder()
- .url(url).get()
- .addHeader("Cookie", getCookie(context))
- .cacheControl(CacheControl.FORCE_NETWORK)
- .build();
- client.newCall(request).enqueue(callback);
- }
-
- /**
- * 发送json数据
- *
- * @param url 请求地址
- * @param paramJson 发送json数据
- * @param callback 执行函数
- */
- public void postJson(String url, JSONObject paramJson, final Callback callback) {
- OkHttpClient client = new OkHttpClient();
- RequestBody requestBody = OkHttpUtils.setJSONBody(paramJson.toJSONString());
- Request request = new Request.Builder()
- .url(splicingUrl(url)).post(requestBody)
- .cacheControl(CacheControl.FORCE_NETWORK)
- .build();
- client.newCall(request).enqueue(callback);
- }
-
-
- /**
- * 发送表单数据
- *
- * @param url 请求地址
- * @param paramJson 请求参数
- * @param callback 执行函数
- */
- public void postForm(Context context, String url, JSONObject paramJson, final Callback callback) {
- OkHttpClient client = new OkHttpClient();
- RequestBody requestBody = OkHttpUtils.setFormBody(paramJson);
- Request request = new Request.Builder()
- .url(splicingUrl(url)).post(requestBody)
- .addHeader("Cookie", getCookie(context))
- .cacheControl(CacheControl.FORCE_NETWORK)
- .build();
- client.newCall(request).enqueue(callback);
- }
-
-
- /**
- * 发送表单数据
- *
- * @param url 请求地址
- * @param paramJson 请求参数
- * @param callback 执行函数
- */
- public void postFormByLogin(Context context, String url, JSONObject paramJson, final Callback callback) {
- OkHttpClient client = new OkHttpClient();
- RequestBody requestBody = OkHttpUtils.setFormBody(paramJson);
- Request request = new Request.Builder()
- .url(splicingUrl(url)).post(requestBody)
- .cacheControl(CacheControl.FORCE_NETWORK)
- .build();
- client.newCall(request).enqueue(callback);
- }
-
- /**
- * 单例模式获取RequestUtils
- *
- * @return RequestUtils
- */
- public static RequestUtils getInstance() {
- if (mInstance == null) {
- synchronized (LOCKER) {
- if (mInstance == null) {
- mInstance = new RequestUtils();
- }
- }
- }
- return mInstance;
- }
-
- /**
- * 组合请求地址
- *
- * @param url 映射地址
- * @return 请求地址
- */
- private String splicingUrl(String url) {
- return SysConst.REMOTE_URL + url;
- }
-
-
- /**
- * 获取登录信息
- *
- * @param context 上下文对象
- * @return String
- */
- public String getCookie(Context context) {
- String sessionId = SharedPrefUtils.getInstance().getStrBykey(CacheKeys.LOGIN_SESSION_Id, StringUtil.EMPTY_STRING);
- if (sessionId.equals(StringUtil.EMPTY_STRING)) {
- return SysConst.EMPTY;
- } else {
- return sessionId;
- }
- }
-
- }
(2).CacheKeys是对登录的cookie做缓存的key的一个常量
- package com.zjxf.cache;
-
- /**
- * created with IntelliJ IDEA
- *
- * @author: create by limu
- * Date: 2020/4/9
- * Time:10:31
- */
- public class CacheKeys {
-
- public final static String LOGIN_USERNAME = "login_user_name:";
- public final static String THIS_SCHOOL_NAME = "this_school_name:";
- public final static String LOGIN_SESSION_Id = "login_session_id:";
-
-
- }
(3).SysConst是对系统常量类的一个管理
- package com.zjxf.common;
-
-
- /**
- * created with IntelliJ IDEA
- * <p>
- * 系统常量类
- * <p>
- * Date: 2020/2/12
- *
- * @author: create by limu
- * Time:16:23
- */
- public class SysConst {
-
- public static final String REMOTE_URL = "http://39.100.143.199:8631"; //远程请求地址 后缀不加斜杆
- }
3.用法
- JSONObject paramJson = new JSONObject();
- paramJson.put("bankId", bankId);
-
- RequestUtils.getInstance().postForm(AnswerActivity.this, ResourceManagerUrlConstants.PSY_APP_FIND_BY_TOPICS, paramJson, new Callback() {
- @Override
- public void onFailure(Call call, IOException e) {
- runOnUiThread(() -> ToastUtils.showToastUnLine(AnswerActivity.this));
- }
-
- @Override
- public void onResponse(Call call, Response response) throws IOException {
- String resultData = ResultUtils.getResultData(response, AnswerActivity.this);
- }
- });
以上是发送form表单数据时候使用的,工具类中也提供发生json数据的方法,也提供不发送数据的方法,大家有什么疑问可以在博客下方留言。
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。