当前位置: 移动技术网 > IT编程>移动开发>Android > Android中Retrofit 2.0直接使用JSON进行数据交互

Android中Retrofit 2.0直接使用JSON进行数据交互

2019年07月24日  | 移动技术网IT编程  | 我要评论

新梁山伯与祝英台何润东,高清mv网站,黄晓明聚会上无视马云

之前使用retrofit都是将json串转化为pojo对象,针对不同的业务协议,定义相应的接口和参数列表。但是此种方式一般用在自己内部协议基础上,具体大的项目中,有些第三方的集成功能,一般都采用统一的方式即请求json和回应json进行数据交互,不可能每个第三方协议都会去定义与协议相应的pojo对象。

http肯定有get和post方法,先定义retrofit api的interface:

package com.hdnetworklib.network.http;

import java.util.map;

import okhttp3.requestbody;
import okhttp3.responsebody;
import retrofit2.call;
import retrofit2.http.body;
import retrofit2.http.get;
import retrofit2.http.post;
import retrofit2.http.querymap;
import retrofit2.http.url;

/**
 * created by wangyuhang@evergrande.cn on 2017/8/23 0023.
 */

public interface retrofitserviceapi {
  @post
  call<responsebody> reqpost(@url string url, @body requestbody requestbody);

  @get
  call<responsebody> reqget(@url string url, @querymap map<string, string> options);

  @get
  call<responsebody> reqget(@url string url);
}

1、post方式,采用指定完整的url,reqeustbody就是后面业务要传入的完整json串

2、get方式,后面的options就是一个map,业务参数键值就存在这个里面,url里面不需要带值。

3、get方式,与2不同的是没有options,这样就键值对全部带在url里面,类似于这样的格式:http://112.124.22.238:8081/course_api/wares/hot?pagesize=1&curpage=1

接下来就是具体对业务的接口了,提供post和get两个请求接口调用:

package com.hdnetworklib.network.http;

import android.util.log;

import java.io.ioexception;
import java.util.map;

import okhttp3.mediatype;
import okhttp3.requestbody;
import okhttp3.responsebody;
import retrofit2.call;
import retrofit2.callback;
import retrofit2.response;
import retrofit2.retrofit;
import retrofit2.converter.gson.gsonconverterfactory;

/**
 * created by wangyuhang@evergrande.cn on 2017/7/12 0012.
 */

public class httpclient {
  private static final string tag = "httpclient";
  private static volatile httpclient instance;

  private httpclient() {
  }

  public static httpclient getinstance() {
    if (instance == null) {
      synchronized (httpclient.class) {
        if (instance == null) {
          instance = new httpclient();
        }
      }
    }

    return instance;
  }

  /**
   * http post请求
   *
   * @param req_id  请求编号
   * @param method  请求业务方法
   * @param url   请求的url
   * @param jsondata post需要所带参数(json串格式)
   * @param callback 回调接口
   */
  public void reqposthttp(final int req_id, final string method, string url, string jsondata, final httpcallback callback) {
    retrofit retrofit = new retrofit.builder()
        .baseurl("http://www.what.com/")
        .addconverterfactory(gsonconverterfactory.create())
        .build();

    retrofitserviceapi retrofitserviceapi = retrofit.create(retrofitserviceapi.class);

    requestbody body = requestbody.create(mediatype.parse("application/json; charset=utf-8"), jsondata);

    call<responsebody> call = retrofitserviceapi.reqpost(url, body);
    call.enqueue(new callback<responsebody>() {
      @override
      public void onresponse(call<responsebody> call, response<responsebody> response) {
        try {
          string result = response.body().string();
          log.i(tag, "reqposthttp onresponse: " + result);

          if (callback != null) {
            callback.onsuccess(new httpresmsg(req_id, method, result));
          }
        } catch (ioexception e) {
          e.printstacktrace();
          log.e(tag, "reqposthttp onresponse exception: " + e.tostring());

          if (callback != null) {
            callback.onerror(e.tostring());
          }
        }
      }

      @override
      public void onfailure(call<responsebody> call, throwable t) {
        log.e(tag, "reqposthttp onfailure: " + t.tostring());

        if (callback != null) {
          callback.onerror(t.tostring());
        }
      }
    });
  }

  /**
   * http get请求
   *
   * @param req_id  请求编号
   * @param method  请求业务方法
   * @param url   请求的url
   * @param options get需要所带参数键值(如果url里带有则不需要在此添加)
   * @param callback 回调接口
   */
  public void reqgethttp(final int req_id, final string method, string url,
              map<string, string> options, final httpcallback callback) {
    retrofit retrofit = new retrofit.builder()
        .baseurl("http://www.what.com/")
        .addconverterfactory(gsonconverterfactory.create())
        .build();

    retrofitserviceapi retrofitserviceapi = retrofit.create(retrofitserviceapi.class);

    call<responsebody> call = null;
    if (options == null) {
      call = retrofitserviceapi.reqget(url);
    } else {
      call = retrofitserviceapi.reqget(url, options);
    }

    call.enqueue(new callback<responsebody>() {
      @override
      public void onresponse(call<responsebody> call, response<responsebody> response) {
        try {
          string result = response.body().string();
          log.i(tag, "reqposthttp onresponse: " + result);

          if (callback != null) {
            callback.onsuccess(new httpresmsg(req_id, method, result));
          }
        } catch (ioexception e) {
          e.printstacktrace();
          log.e(tag, "reqposthttp onresponse exception: " + e.tostring());

          if (callback != null) {
            callback.onerror(e.tostring());
          }
        }
      }

      @override
      public void onfailure(call<responsebody> call, throwable t) {
        log.e(tag, "reqposthttp onfailure: " + t.tostring());
        if (callback != null) {
          callback.onerror(t.tostring());
        }
      }
    });
  }
}

需要注意的是:

baseurl(http://www.what.com/)

这里的这个baseurl是我瞎掰的一个地址,因为retrofit的限制:如果baseurl不是以 / 结尾就会报异常:

caused by: java.lang.illegalargumentexception: baseurl must end in /

当我们需要完整的指定url的时候,特别是上面列出的第二种get方式,我们的url是http://112.124.22.238:8081/course_api/wares/hot?pagesize=1&curpage=1,如果我们直接通过接口传参把这个url直接传入baseurl中,如下(注意最后没有/结尾):

retrofit retrofit = new retrofit.builder()
        .baseurl("http://112.124.22.238:8081/course_api/wares/hot?pagesize=1&curpage=1")
        .addconverterfactory(gsonconverterfactory.create())
        .build();

这样运行时就会报错。那如果我们手工在最后面加上一个/呢?如下(注意最后有/结尾):

retrofit retrofit = new retrofit.builder()
        .baseurl("http://112.124.22.238:8081/course_api/wares/hot?pagesize=1&curpage=1/")
        .addconverterfactory(gsonconverterfactory.create())
        .build();

这样运行时仍然报错,而且你把这个链接复制到浏览器中看看就知道肯定不行的:http://112.124.22.238:8081/course_api/wares/hot?pagesize=1&curpage=1/

我一开始遇到这个问题的时候也是第一反应去查retrofit的官方文档和说明,或者让第三方的开发人员采用第二种get请求方式,用一个以 / 结尾的url,然后把url中?后面带的那些值放到一个map里传进来。首先官方说明和api用法没找到,而且这个baseurl还必须调用,其次,别的开发人员不愿意弄,好好的辛辛苦苦把url都组装好了,没啥事让我传map啊,肯定也不行。后面在这里找到了答案:


所以既然你后面会完整指定url,那么一开始的baseurl就无关紧要,随便写一个以/结尾的http地址就可以了。

剩下的的就是回调和消息的组装了,各位可以根据自己的业务需求进行组装和调整,我这里就只贴出代码不做过多解析了。

回调接口:

package com.hdnetworklib.network.http;

/**
 * created by wangyuhang@evergrande.cn on 2017/8/23 0023.
 */

public interface httpcallback {
  void onsuccess(httpresmsg httpresmsg);

  void onerror(string errormsg);
}

消息结构的组装:

package com.hdnetworklib.network.http;

/**
 * created by wangyuhang@evergrande.cn on 2017/8/23 0023.
 */

public class httpresmsg {
  private integer req_id;
  private string method;
  private string data;

  public httpresmsg() {
  }

  public httpresmsg(int req_id, string method, string data) {
    this.req_id = req_id;
    this.method = method;
    this.data = data;
  }

  public integer getreq_id() {
    return req_id;
  }

  public void setreq_id(integer req_id) {
    this.req_id = req_id;
  }

  public string getmethod() {
    return method;
  }

  public void setmethod(string method) {
    this.method = method;
  }

  public string getdata() {
    return data;
  }

  public void setdata(string data) {
    this.data = data;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网