栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

android Retrofit请求体加密 body加密

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

android Retrofit请求体加密 body加密

更改Converter.Factory 加密
  1. Retrofit请求体加密,需要自己去写Factory
public class JsonConverterFactory extends Converter.Factory {
    private static final String TAG = "JsonConverterFactory";
    private final Gson gson;

    public static JsonConverterFactory create() {
        return create(new Gson());
    }

    public static JsonConverterFactory create(Gson gson) {
        return new JsonConverterFactory(gson);

    }

    private JsonConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }


    @Nullable
    @Override
    public Converter requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter adapter = gson.getAdapter(TypeToken.get(type));
        return new JsonRequestBodyConverter<>(gson, adapter); //请求
    }

    @Nullable
    @Override
    public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {

        TypeAdapter adapter = gson.getAdapter(TypeToken.get(type));
        //TypeAdapter adapter = gson.getAdapter(new TypeToken<>(){}.getType());
        return new JsonResponseBodyConverter<>(gson, adapter); //响应
    }

    
    public static class JsonRequestBodyConverter implements Converter {
        private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
        private final Gson gson;
        private final TypeAdapter adapter;

        
        public JsonRequestBodyConverter(Gson gson, TypeAdapter adapter) {
            this.gson = gson;
            this.adapter = adapter;
        }

        @Override
        public RequestBody convert(T value) throws IOException {

            //这里需要,特别注意的是,request是将T转换成json数据。
            //你要在T转换成json之后再做加密。
            //再将数据post给服务器,同时要注意,你的T到底指的那个对象   这个加密请求体 转换为用自己的加密方式
            String byteDecrypt = DESUtils.encrypt(value.toString(), "");
           // Log.e("=====>", "request中传递的json数据:" + value.toString()); //打印:加密前的json字符串
           // Log.e("=====>", "加密后的字节数组:" + byteDecrypt.toString());//打印:字节数组

            //传入字节数组,创建RequestBody 对象
            return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),byteDecrypt);
        }
    }

    
    public class JsonResponseBodyConverter implements Converter {
        private final Gson mGson;//gson对象
        private final TypeAdapter adapter;

        
        public JsonResponseBodyConverter(Gson gson, TypeAdapter adapter) {
            this.mGson = gson;
            this.adapter = adapter;
        }

        
        @Override
        public T convert(ResponseBody responseBody) throws IOException {

      
			// 如果想解密 在这里也可以解密  然后把数据传回去  我在返回数据那里解密	
            //这部分代码参考GsonConverterFactory中GsonResponseBodyConverter的源码对json的处理
            Reader reader = StringToReader(responseBody.string().toString().trim());
            JsonReader jsonReader = gson.newJsonReader(reader);
            try {
                return adapter.read(jsonReader);
            } finally {
                reader.close();
                jsonReader.close();
            }
        }

        
        private Reader StringToReader(String json){
            Reader reader  = new StringReader(json);
            return reader;
        }
    }

  1. 加密需要传入的参数是body
 // 这里的数据类型ResponseBody 由根据上面的返回数据类型得到的
 @POST(".....")
    Call health_1(@Body String s);
  1. 用Retrofit 发起请求
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http:....")
                              .addConverterFactory(JsonConverterFactory.create())
                             .build();
 	Map map = new HashMap<>();
	map...
	Gson gson = new Gson();
	String s = gson.toJson(map);
	//    ...传入步骤2中的interface类的类名
	Call call = retrofit.create(...).health_1(s);
    call.enqueue(....);
另一种加密
  1. 正常写GsonConverterFactory.create()
Retrofit retrofit = new Retrofit.Builder().baseUrl("http:...")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
  1. 正常写请求
@POST("...")
    Callup_record(@Body RequestBody s);
  1. 发起请求
 Retrofit retrofit = new Retrofit.Builder().baseUrl("http:...")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Map map = new HashMap<>();
        map....
        Gson gson = new Gson();
        String s = gson.toJson(map);
        String s1 = DESUtils.encrypt(s,""); // 加密方式
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), s1); // json 文本请求
        Call call = retrofit.create(IHP.class).up_record(body);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String decryptString = DESUtils.decrypt(response.body().string(), ""); // 解密 获取数据
                  
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
              
            }
        });
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970940.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号