1package com.squareup.okhttp.apache;
2
3import com.squareup.okhttp.MediaType;
4import com.squareup.okhttp.RequestBody;
5import java.io.IOException;
6import okio.BufferedSink;
7import org.apache.http.HttpEntity;
8
9/** Adapts an {@link HttpEntity} to OkHttp's {@link RequestBody}. */
10final class HttpEntityBody extends RequestBody {
11  private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.parse("application/octet-stream");
12
13  private final HttpEntity entity;
14  private final MediaType mediaType;
15
16  HttpEntityBody(HttpEntity entity, String contentTypeHeader) {
17    this.entity = entity;
18
19    if (contentTypeHeader != null) {
20      mediaType = MediaType.parse(contentTypeHeader);
21    } else if (entity.getContentType() != null) {
22      mediaType = MediaType.parse(entity.getContentType().getValue());
23    } else {
24      // Apache is forgiving and lets you skip specifying a content type with an entity. OkHttp is
25      // not forgiving so we fall back to a generic type if it's missing.
26      mediaType = DEFAULT_MEDIA_TYPE;
27    }
28  }
29
30  @Override public long contentLength() {
31    return entity.getContentLength();
32  }
33
34  @Override public MediaType contentType() {
35    return mediaType;
36  }
37
38  @Override public void writeTo(BufferedSink sink) throws IOException {
39    entity.writeTo(sink.outputStream());
40  }
41}
42