服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - android 使用okhttp可能引发OOM的一个点

android 使用okhttp可能引发OOM的一个点

2022-11-03 15:11林鹿 Android

这篇文章主要介绍了android 使用okhttp可能引发OOM的一个点,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

遇到一个问题: 需要给所有的请求加签名校验以防刷接口;传入请求url及body生成一个文本串作为一个header传给服务端;已经有现成的签名检验方法String doSignature(String url, byte[] body);当前网络库基于com.squareup.okhttp3:okhttp:3.14.2.
这很简单了,当然是写一个interceptor然后将request对象的url及body传入就好.于是有:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class SignInterceptor implements Interceptor {
  @NonNull
  @Override
  public Response intercept(@NonNull Chain chain) throws IOException {
    Request request = chain.request();
    RequestBody body = request.body();
    byte[] bodyBytes = null;
    if (body != null) {
      final Buffer buffer = new Buffer();
      body.writeTo(buffer);
      bodyBytes = buffer.readByteArray();
    }
 
    Request.Builder builder = request.newBuilder();
    HttpUrl oldUrl = request.url();
    final String url = oldUrl.toString();
    final String signed = doSignature(url, bodyBytes));
    if (!TextUtils.isEmpty(signed)) {
      builder.addHeader(SIGN_KEY_NAME, signed);
    }
    return chain.proceed(builder.build());
  }
}

okhttp的ReqeustBody是一个抽象类,内容输出只有writeTo方法,将内容写入到一个BufferedSink接口实现体里,然后再将数据转成byte[]也就是内存数组.能达到目的的类只有Buffer,它实现了BufferedSink接口并能提供转成内存数组的方法readByteArray. 这貌似没啥问题呀,能造成OOM?

是的,要看请求类型,如果是一个上传文件的接口呢?如果这个文件比较大呢?上传接口有可能会用到public static RequestBody create(final @Nullable MediaType contentType, final File file)方法,如果是针对文件的实现体它的writeTo方法是sink.writeAll(source);而我们传给签名方法时用到的Buffer.readByteArray是将缓冲中的所有内容转成了内存数组, 这意味着文件中的所有内容被转成了内存数组, 就是在这个时机容易造成OOM! RequestBody.create源码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static RequestBody create(final @Nullable MediaType contentType, final File file) {
 if (file == null) throw new NullPointerException("file == null");
 
 return new RequestBody() {
  @Override public @Nullable MediaType contentType() {
   return contentType;
  }
 
  @Override public long contentLength() {
   return file.length();
  }
 
  @Override public void writeTo(BufferedSink sink) throws IOException {
   try (Source source = Okio.source(file)) {
    sink.writeAll(source);
   }
  }
 };
}

可以看到实现体持有了文件,Content-Length返回了文件的大小, 内容全部转给了Source对象。

这确实是以前非常容易忽略的一个点,很少有对请求体作额外处理的操作,而一旦这个操作变成一次性的大内存分配, 非常容易造成OOM. 所以要如何解决呢? 签名方法又是如何处理的呢? 原来这个签名方法在这里偷了个懒——它只读取传入body的前4K内容,然后只针对这部分内容进行了加密,至于传入的这个内存数组本身多大并不考虑,完全把风险和麻烦丢给了外部(优秀的SDK!).

快速的方法当然是罗列白名单,针对上传接口服务端不进行加签验证, 但这容易挂一漏万,而且增加维护成本, 要签名方法sdk的人另写合适的接口等于要他们的命, 所以还是得从根本解决. 既然签名方法只读取前4K内容,我们便只将内容的前4K部分读取再转成方法所需的内存数组不就可了? 所以我们的目的是: 期望RequestBody能够读取一部分而不是全部的内容. 能否继承RequestBody重写它的writeTo? 可以,但不现实,不可能全部替代现有的RequestBody实现类, 同时ok框架也有可能创建私有的实现类. 所以只能针对writeTo的参数BufferedSink作文章, 先得了解BufferedSink又是如何被okhttp框架调用的.

BufferedSink相关的类包括Buffer, Source,都属于okio框架,okhttp只是基于okio的一坨, okio没有直接用java的io操作,而是另行写了一套io操作,具体是数据缓冲的操作.接上面的描述, Source是怎么创建, 同时又是如何操作BufferedSink的? 在Okio.java中:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public static Source source(File file) throws FileNotFoundException {
 if (file == null) throw new IllegalArgumentException("file == null");
 return source(new FileInputStream(file));
}
 
public static Source source(InputStream in) {
 return source(in, new Timeout());
}
 
private static Source source(final InputStream in, final Timeout timeout) {
 return new Source() {
  @Override public long read(Buffer sink, long byteCount) throws IOException {
   try {
    timeout.throwIfReached();
    Segment tail = sink.writableSegment(1);
    int maxToCopy = (int) Math.min(byteCount, Segment.SIZE - tail.limit);
    int bytesRead = in.read(tail.data, tail.limit, maxToCopy);
    if (bytesRead == -1) return -1;
    tail.limit += bytesRead;
    sink.size += bytesRead;
    return bytesRead;
   } catch (AssertionError e) {
    if (isAndroidGetsocknameError(e)) throw new IOException(e);
    throw e;
   }
  }
 
  @Override public void close() throws IOException {
   in.close();
  }
 
  @Override public Timeout timeout() {
   return timeout;
  }
 };
}

Source把文件作为输入流inputstream进行了各种读操作, 但是它的read方法参数却是个Buffer实例,它又是从哪来的,又怎么和BufferedSink关联的? 只好再继续看BufferedSink.writeAll的实现体。

BufferedSink的实现类就是Buffer, 然后它的writeAll方法:

?
1
2
3
4
5
6
7
8
@Override public long writeAll(Source source) throws IOException {
 if (source == null) throw new IllegalArgumentException("source == null");
 long totalBytesRead = 0;
 for (long readCount; (readCount = source.read(this, Segment.SIZE)) != -1; ) {
  totalBytesRead += readCount;
 }
 return totalBytesRead;
}

原来是显式的调用了Source.read(Buffer,long)方法,这样就串起来了,那个Buffer参数原来就是自身。

基本可以确定只要实现BufferedSink接口类, 然后判断读入的内容超过指定大小就停止写入就返回就可满足目的, 可以名之FixedSizeSink.

然而麻烦的是BufferedSink的接口非常多, 将近30个方法, 不知道框架会在什么时机调用哪个方法,只能全部都实现! 其次是接口方法的参数有很多okio的类, 这些类的用法需要了解, 否则一旦用错了效果适得其反. 于是对一个类的了解变成对多个类的了解, 没办法只能硬着头皮写.

第一个接口就有点蛋疼: Buffer buffer(); BufferedSink返回一个Buffer实例供外部调用, BufferedSink的实现体即是Buffer, 然后再返回一个Buffer?! 看了半天猜测BufferedSink是为了提供一个可写入的缓冲对象, 但框架作者也懒的再搞接口解耦的那一套了(唉,大家都是怎么简单怎么来). 于是FixedSizeSink至少需要持有一个Buffer对象, 它作实际的数据缓存,同时可以在需要Source.read(Buffer ,long)的地方作为参数传过去.

同时可以看到RequestBody的一个实现类FormBody, 用这个Buffer对象直接写入一些数据:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private long writeOrCountBytes(@Nullable BufferedSink sink, boolean countBytes) {
 long byteCount = 0L;
 
 Buffer buffer;
 if (countBytes) {
  buffer = new Buffer();
 } else {
  buffer = sink.buffer();
 }
 
 for (int i = 0, size = encodedNames.size(); i < size; i++) {
  if (i > 0) buffer.writeByte('&');
  buffer.writeUtf8(encodedNames.get(i));
  buffer.writeByte('=');
  buffer.writeUtf8(encodedValues.get(i));
 }
 
 if (countBytes) {
  byteCount = buffer.size();
  buffer.clear();
 }
 
 return byteCount;
}

有这样的操作就有可能限制不了缓冲区大小变化!不过数据量应该相对小一些而且这种用法场景相对少,我们指定的大小应该能覆盖的了这种情况。

接着还有一个接口BufferedSink write(ByteString byteString), 又得了解ByteString怎么使用, 真是心力交瘁啊...

?
1
2
3
4
@Override public Buffer write(ByteString byteString) {
 byteString.write(this);
 return this;
}

Buffer实现体里可以直接调用ByteString.write(Buffer)因为是包名访问,自己实现的FixedSizeSink声明在和同一包名package okio;也可以这样使用,如果是其它包名只能先转成byte[]了, ByteString应该不大不然也不能这么搞(没有找到ByteString读取一段数据的方法):

?
1
2
3
4
5
6
@Override
public BufferedSink write(@NotNull ByteString byteString) throws IOException {
  byte[] bytes = byteString.toByteArray();
  this.write(bytes);
  return this;
}

总之就是把这些对象转成内存数组或者Buffer能够接受的参数持有起来!

重点关心的writeAll反而相对好实现一点, 我们连续读取指定长度的内容直到内容长度达到我们的阈值就行.

还有一个蛋疼的点是各种对象的read/write数据流方向:

Caller.read(Callee)/Caller.write(Callee), 有的是从Caller到Callee, 有的是相反,被一个小类整的有点头疼……

最后上完整代码, 如果发现什么潜在的问题也可以交流下~:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
public class FixedSizeSink implements BufferedSink {
  private static final int SEGMENT_SIZE = 4096;
  private final Buffer mBuffer = new Buffer();
  private final int mLimitSize;
 
  private FixedSizeSink(int size) {
    this.mLimitSize = size;
  }
 
  @Override
  public Buffer buffer() {
    return mBuffer;
  }
 
  @Override
  public BufferedSink write(@NotNull ByteString byteString) throws IOException {
    byte[] bytes = byteString.toByteArray();
    this.write(bytes);
    return this;
  }
 
  @Override
  public BufferedSink write(@NotNull byte[] source) throws IOException {
    this.write(source, 0, source.length);
    return this;
  }
 
  @Override
  public BufferedSink write(@NotNull byte[] source, int offset,
      int byteCount) throws IOException {
    long available = mLimitSize - mBuffer.size();
    int count = Math.min(byteCount, (int) available);
    android.util.Log.d(TAG, String.format("FixedSizeSink.offset=%d,"
             "count=%d,limit=%d,size=%d",
        offset, byteCount, mLimitSize, mBuffer.size()));
    if (count > 0) {
      mBuffer.write(source, offset, count);
    }
    return this;
  }
 
  @Override
  public long writeAll(@NotNull Source source) throws IOException {
    this.write(source, mLimitSize);
    return mBuffer.size();
  }
 
  @Override
  public BufferedSink write(@NotNull Source source, long byteCount) throws IOException {
    final long count = Math.min(byteCount, mLimitSize - mBuffer.size());
    final long BUFFER_SIZE = Math.min(count, SEGMENT_SIZE);
    android.util.Log.d(TAG, String.format("FixedSizeSink.count=%d,limit=%d"
             ",size=%d,segment=%d",
        byteCount, mLimitSize, mBuffer.size(), BUFFER_SIZE));
    long totalBytesRead = 0;
    long readCount;
    while (totalBytesRead < count && (readCount = source.read(mBuffer, BUFFER_SIZE)) != -1) {
      totalBytesRead = readCount;
    }
    return this;
  }
 
  @Override
  public int write(ByteBuffer src) throws IOException {
    final int available = mLimitSize - (int) mBuffer.size();
    if (available < src.remaining()) {
      byte[] bytes = new byte[available];
      src.get(bytes);
      this.write(bytes);
      return bytes.length;
    } else {
      return mBuffer.write(src);
    }
  }
 
  @Override
  public void write(@NotNull Buffer source, long byteCount) throws IOException {
    mBuffer.write(source, Math.min(byteCount, mLimitSize - mBuffer.size()));
  }
 
  @Override
  public BufferedSink writeUtf8(@NotNull String string) throws IOException {
    mBuffer.writeUtf8(string);
    return this;
  }
 
  @Override
  public BufferedSink writeUtf8(@NotNull String string, int beginIndex, int endIndex)
      throws IOException {
    mBuffer.writeUtf8(string, beginIndex, endIndex);
    return this;
  }
 
  @Override
  public BufferedSink writeUtf8CodePoint(int codePoint) throws IOException {
    mBuffer.writeUtf8CodePoint(codePoint);
    return this;
  }
 
  @Override
  public BufferedSink writeString(@NotNull String string,
      @NotNull Charset charset) throws IOException {
    mBuffer.writeString(string, charset);
    return this;
  }
 
  @Override
  public BufferedSink writeString(@NotNull String string, int beginIndex, int endIndex,
      @NotNull Charset charset) throws IOException {
    mBuffer.writeString(string, beginIndex, endIndex, charset);
    return this;
  }
 
  @Override
  public BufferedSink writeByte(int b) throws IOException {
    mBuffer.writeByte(b);
    return this;
  }
 
  @Override
  public BufferedSink writeShort(int s) throws IOException {
    mBuffer.writeShort(s);
    return this;
  }
 
  @Override
  public BufferedSink writeShortLe(int s) throws IOException {
    mBuffer.writeShortLe(s);
    return this;
  }
 
  @Override
  public BufferedSink writeInt(int i) throws IOException {
    mBuffer.writeInt(i);
    return this;
  }
 
  @Override
  public BufferedSink writeIntLe(int i) throws IOException {
    mBuffer.writeIntLe(i);
    return this;
  }
 
  @Override
  public BufferedSink writeLong(long v) throws IOException {
    mBuffer.writeLong(v);
    return this;
  }
 
  @Override
  public BufferedSink writeLongLe(long v) throws IOException {
    mBuffer.writeLongLe(v);
    return this;
  }
 
  @Override
  public BufferedSink writeDecimalLong(long v) throws IOException {
    mBuffer.writeDecimalLong(v);
    return this;
  }
 
  @Override
  public BufferedSink writeHexadecimalUnsignedLong(long v) throws IOException {
    mBuffer.writeHexadecimalUnsignedLong(v);
    return this;
  }
 
  @Override
  public void flush() throws IOException {
    mBuffer.flush();
  }
 
  @Override
  public BufferedSink emit() throws IOException {
    mBuffer.emit();
    return this;
  }
 
  @Override
  public BufferedSink emitCompleteSegments() throws IOException {
    mBuffer.emitCompleteSegments();
    return this;
  }
 
  @Override
  public OutputStream outputStream() {
    return mBuffer.outputStream();
  }
 
  @Override
  public boolean isOpen() {
    return mBuffer.isOpen();
  }
 
  @Override
  public Timeout timeout() {
    return mBuffer.timeout();
  }
 
  @Override
  public void close() throws IOException {
    mBuffer.close();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://juejin.im/post/5da32c9a5188255aa15d4312

延伸 · 阅读

精彩推荐