【Android】Retrofit的使用(2)-使用Retrofit提交JSON数据

在公司的实际项目需求中,我们请求网络接口很多已经脱离简单的post与get方法,采用json的数据格式以流的形式来进行上传,那么怎么用Retrofit去实现呢?1.首先我们需要创建一个Converte

by
江江
on
2016/09/12

在公司的实际项目需求中,我们请求网络接口很多已经脱离简单的post与get方法,采用json的数据格式以流的形式来进行上传,那么怎么用Retrofit去实现呢?

1.首先我们需要创建一个ConverterFactory类,通过它来对请求数据与接收数进行装换

public final class JsonConverterFactory extends Converter.Factory {
    private JSONObject jsonObject;
    public static JsonConverterFactory create() {
        return create(new JSONObject());
    }
    private static JsonConverterFactory create(JSONObject jsonObject) {
        return new JsonConverterFactory(jsonObject);
    }
    private JsonConverterFactory(JSONObject jsonObject) {
        if (jsonObject == null)throw new NullPointerException("json == null");
        this.jsonObject = jsonObject;
    }
    @Override
    public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
        return new JsonResponseBodyConverter<>(jsonObject);
    }

    @Override public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
        return new JsonRequestBodyConverter<>(jsonObject);
    }
}

2.JsonRequestBodyConverter类

/**
 * Created by ccwant on 2016/8/19.
 */
final class JsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private JSONObject jsonObject;
    JsonRequestBodyConverter(JSONObject jsonObject) {

        this.jsonObject=jsonObject;
    }
    @Override
    public RequestBody convert(T value) throws IOException {
        Buffer buffer = new Buffer();
        Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
        Log.d("123","提交数据:"+value.toString());
        writer.write(value.toString());
        writer.close();
        return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
    }
}

3.JsonResponseBodyConverter类

/**
 * Created by ccwant on 2016/8/19.
 */
final class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private JSONObject jsonObject;
    JsonResponseBodyConverter(JSONObject jsonObject) {

    }
    @Override
    public T convert(ResponseBody value) throws IOException {
        BufferedReader br=new BufferedReader(value.charStream());
        String line="";
        StringBuffer buffer = new StringBuffer();
        while((line=br.readLine())!=null){
            buffer.append(line);
        }
        //buffer.toString()
        Log.d("123","接收数据:"+buffer.toString());
        try {
            jsonObject=new JSONObject(buffer.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return (T)jsonObject;
    }
}

4.使用方法 在实例化Retrofit的时候

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)//传递url
                .client(client)
                .addConverterFactory(JsonConverterFactory.create())//添加转换器
                .build();

在http的service我们这么写

@POST("login.json")
Call<JSONObject> login(@Body JSONObject parmas);

在网络请求的回调方法中

call.enqueue(new Callback<JSONObject>() {
    @Override
    public void onResponse(Response<JSONObject> response, Retrofit retrofit) {
    }
    @Override
    public void onFailure(Throwable t) {
    }
});
江江江江于 2026-10-12 13:35:43 修改阅读 6449评论 0点赞 0