【问题标题】:Retrofit 2 append @Body request改造 2 追加 @Body 请求
【发布时间】:2017-02-27 14:28:06
【问题描述】:

我想使用带有 @Body 注释的 HTTP 请求正文拦截我的所有改造调用,并用新生成的字符串附加它们。

到目前为止,我设法拦截了正文并生成了字符串,但无法将其添加到请求中。

我使用了这个答案here,但 writeTo() 方法似乎将我的参数添加为@Field,而不是在实际的请求正文中。

【问题讨论】:

    标签: android retrofit retrofit2


    【解决方案1】:

    我在旧请求正文中添加“token”:“value”

    public static Request interceptRequest(Request request)
            throws IOException {
    
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        Sink sink = Okio.sink(baos);
        BufferedSink bufferedSink = Okio.buffer(sink);
    
        /**
         * Write old params
         * */
        request.body().writeTo(bufferedSink);
    
        if (UserModelManager.getInstance().isLogin()) {
            String hasd = bufferedSink.buffer().readString(Charset.defaultCharset());//result like this [text={}]
            Pattern pattern = Pattern.compile("\\{.*\\}");
            Matcher matcher = pattern.matcher(hasd);
    
            if(matcher.find()){
                String oldBody = matcher.group();
                try {
                    JSONObject jsonObject = new JSONObject(oldBody);
                    jsonObject.put("token", UserModelManager.getInstance().getUser().token);
                    bufferedSink.flush();
    
                    bufferedSink.writeString(jsonObject.toString(), Charset.defaultCharset());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
    
            }
        }
        /**
         * write to buffer additional params
         * */
    
    
    
    
        RequestBody newRequestBody = RequestBody.create(
                request.body().contentType(),
                bufferedSink.buffer().readUtf8()
        );
        return request.newBuilder().post(newRequestBody).build();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 2022-07-25
      相关资源
      最近更新 更多