1 package com.squareup.okhttp.apache; 2 3 import com.squareup.okhttp.MediaType; 4 import com.squareup.okhttp.RequestBody; 5 import java.io.IOException; 6 import okio.BufferedSink; 7 import org.apache.http.HttpEntity; 8 9 /** Adapts an {@link HttpEntity} to OkHttp's {@link RequestBody}. */ 10 final 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 HttpEntityBody(HttpEntity entity, String contentTypeHeader)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 contentLength()30 @Override public long contentLength() { 31 return entity.getContentLength(); 32 } 33 contentType()34 @Override public MediaType contentType() { 35 return mediaType; 36 } 37 writeTo(BufferedSink sink)38 @Override public void writeTo(BufferedSink sink) throws IOException { 39 entity.writeTo(sink.outputStream()); 40 } 41 } 42