retrofit.mime.TypedOutput Java Examples

The following examples show how to use retrofit.mime.TypedOutput. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Ok3Client.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
private static RequestBody createRequestBody(final TypedOutput body) {
  if (body == null) {
    return null;
  }
  final MediaType mediaType = MediaType.parse(body.mimeType());
  return new RequestBody() {
    @Override public MediaType contentType() {
      return mediaType;
    }

    @Override public void writeTo(BufferedSink sink) throws IOException {
      body.writeTo(sink.outputStream());
    }

    @Override public long contentLength() {
      return body.length();
    }
  };
}
 
Example #2
Source File: Request.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
public Request(String method, String url, List<Header> headers, TypedOutput body) {
    if (method == null) {
        throw new NullPointerException("Method must not be null.");
    }
    if (url == null) {
        throw new NullPointerException("URL must not be null.");
    }
    this.method = method;
    this.url = url;

    if (headers == null) {
        this.headers = Collections.emptyList();
    } else {
        this.headers = Collections.unmodifiableList(new ArrayList<Header>(headers));
    }

    this.body = body;
}
 
Example #3
Source File: ApacheClient.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
GenericHttpRequest(Request request) {
    super();
    method = request.getMethod();
    setURI(URI.create(request.getUrl()));

    // Add all headers.
    for (Header header : request.getHeaders()) {
        addHeader(new BasicHeader(header.getName(), header.getValue()));
    }

    // Add the content body, if any.
    TypedOutput body = request.getBody();
    if (body != null) {
        setEntity(new TypedOutputEntity(body));
    }
}
 
Example #4
Source File: LoganSquareConvertor.java    From hacker-news-android with Apache License 2.0 6 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
    try {
        // Check if the type contains a parametrized list
        if (List.class.isAssignableFrom(object.getClass())) {
            // Convert the input to a list first, access the first element and serialize the list
            List<Object> list = (List<Object>) object;
            if (list.isEmpty()) {
                return new TypedString("[]");
            }
            else {
                Object firstElement = list.get(0);
                return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass()));
            }
        }
        else {
            // Serialize single elements immediately
            return new TypedString(LoganSquare.serialize(object));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: Ok3Client.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
private static RequestBody createRequestBody(final TypedOutput body) {
  if (body == null) {
    return null;
  }
  final MediaType mediaType = MediaType.parse(body.mimeType());
  return new RequestBody() {
    @Override public MediaType contentType() {
      return mediaType;
    }

    @Override public void writeTo(BufferedSink sink) throws IOException {
      body.writeTo(sink.outputStream());
    }

    @Override public long contentLength() {
      return body.length();
    }
  };
}
 
Example #6
Source File: JacksonConverter.java    From android-skeleton-project with MIT License 5 votes vote down vote up
@Override
public TypedOutput toBody(Object o) {
    try {
        return new JsonTypedOutput(objectMapper.writeValueAsString(o).getBytes("UTF-8"));
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}
 
Example #7
Source File: WrapperConverter.java    From Fishing with GNU General Public License v3.0 5 votes vote down vote up
@Override
public TypedOutput toBody(Object o) {
    try {
        return new JsonTypedOutPut(getGson().toJson(o).getBytes(CHARSET_DEFAULT), CHARSET_DEFAULT);
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(e);
    }
}
 
Example #8
Source File: RetrofitCurlClient.java    From libcurldroid with Artistic License 2.0 5 votes vote down vote up
@Override
public Response execute(Request request) throws IOException {
	List<Header> headers = request.getHeaders();
	
	CurlHttp curlHttp = CurlHttp.newInstance();
	
	if (callback != null) {
		callback.afterInit(curlHttp, request.getUrl());
	}
	
	if (headers != null && headers.size() > 0) {
		for (Header header : headers) {
			Log.v(TAG, "add header: " + header.getName() + " " + header.getValue());
			curlHttp.addHeader(header.getName(), header.getValue());
		}
	}
	
	if ("get".equalsIgnoreCase(request.getMethod())) {
		// get
		curlHttp.getUrl(request.getUrl());
	} else {
		// post
		TypedOutput body = request.getBody();
		if (body != null) {
			Log.v(TAG, "set request body");
			ByteArrayOutputStream os = new ByteArrayOutputStream((int) body.length());
			body.writeTo(os);
			curlHttp.setBody(body.mimeType(), os.toByteArray());
		}
		curlHttp.postUrl(request.getUrl());
	}
	return convertResult(request, curlHttp.perform());
}
 
Example #9
Source File: GsonConverter.java    From android-auth-manager with Apache License 2.0 5 votes vote down vote up
@Override public TypedOutput toBody(Object object) {
  try {
    return new JsonTypedOutput(gson.toJson(object).getBytes(charset), charset);
  } catch (UnsupportedEncodingException e) {
    throw new AssertionError(e);
  }
}
 
Example #10
Source File: GsonConverter.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
    try {
        return new JsonTypedOutput(gson.toJson(object).getBytes(encoding), encoding);
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(e);
    }
}
 
Example #11
Source File: RestAdapter.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
private static Profiler.RequestInformation getRequestInfo(String serverUrl, RestMethodInfo methodDetails, Request request) {
    long contentLength = 0;
    String contentType = null;

    TypedOutput body = request.getBody();
    if (body != null) {
        contentLength = body.length();
        contentType = body.mimeType();
    }

    return new Profiler.RequestInformation(methodDetails.requestMethod, serverUrl, methodDetails.requestUrl, contentLength, contentType);
}
 
Example #12
Source File: UrlConnectionClient.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
void prepareRequest(HttpURLConnection connection, Request request) throws IOException {
    // HttpURLConnection artificially restricts request method
    try {
        connection.setRequestMethod(request.getMethod());
    } catch (ProtocolException e) {
        try {
            methodField.set(connection, request.getMethod());
        } catch (IllegalAccessException e1) {
            throw RetrofitError.unexpectedError(request.getUrl(), e1);
        }
    }

    connection.setDoInput(true);

    for (Header header : request.getHeaders()) {
        connection.addRequestProperty(header.getName(), header.getValue());
    }

    TypedOutput body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);
        connection.addRequestProperty("Content-Type", body.mimeType());
        long length = body.length();
        if (length != -1) {
            connection.addRequestProperty("Content-Length", String.valueOf(length));
        }
        body.writeTo(connection.getOutputStream());
    }
}
 
Example #13
Source File: TokenConverter.java    From wear-notify-for-reddit with Apache License 2.0 4 votes vote down vote up
@Override public TypedOutput toBody(Object object) {
    return mOriginalConverter.toBody(object);
}
 
Example #14
Source File: SubscriptionConverter.java    From wear-notify-for-reddit with Apache License 2.0 4 votes vote down vote up
@Override public TypedOutput toBody(Object object) {
    throw new UnsupportedOperationException();
}
 
Example #15
Source File: CommentsConverter.java    From wear-notify-for-reddit with Apache License 2.0 4 votes vote down vote up
@Override public TypedOutput toBody(Object object) {
    return mOriginalConverter.toBody(object);
}
 
Example #16
Source File: RestAdapter.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
/**
 * Log request headers and body. Consumes request body and returns identical replacement.
 */
private Request logAndReplaceRequest(Request request) throws IOException {
    log.log(String.format("---> HTTP %s %s", request.getMethod(), request.getUrl()));

    if (logLevel.ordinal() >= LogLevel.HEADERS.ordinal()) {
        for (Header header : request.getHeaders()) {
            log.log(header.getName() + ": " + header.getValue());
        }

        long bodySize = 0;
        TypedOutput body = request.getBody();
        if (body != null) {
            bodySize = body.length();
            String bodyMime = body.mimeType();

            if (bodyMime != null) {
                log.log("Content-Type: " + bodyMime);
            }
            if (bodySize != -1) {
                log.log("Content-Length: " + bodySize);
            }

            if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) {
                if (!request.getHeaders().isEmpty()) {
                    log.log("");
                }
                if (!(body instanceof TypedByteArray)) {
                    // Read the entire response body to we can log it and replace the original response
                    request = Utils.readBodyToBytesIfNecessary(request);
                    body = request.getBody();
                }

                byte[] bodyBytes = ((TypedByteArray) body).getBytes();
                bodySize = bodyBytes.length;
                String bodyCharset = MimeUtil.parseCharset(bodyMime);
                String bodyString = new String(bodyBytes, bodyCharset);
                for (int i = 0, len = bodyString.length(); i < len; i += LOG_CHUNK_SIZE) {
                    int end = Math.min(len, i + LOG_CHUNK_SIZE);
                    log.log(bodyString.substring(i, end));
                }
            }
        }

        log.log(String.format("---> END HTTP (%s-byte body)", bodySize));
    }

    return request;
}
 
Example #17
Source File: DelegatingConverter.java    From wear-notify-for-reddit with Apache License 2.0 4 votes vote down vote up
@Override public TypedOutput toBody(Object object) {
    return mOriginalConverter.toBody(object);
}
 
Example #18
Source File: RequestBuilder.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
void setArguments(Object[] args) {
    if (args == null) {
        return;
    }
    int count = args.length;
    if (!isSynchronous) {
        count -= 1;
    }
    for (int i = 0; i < count; i++) {
        String name = paramNames[i];
        Object value = args[i];
        RestMethodInfo.ParamUsage paramUsage = paramUsages[i];
        switch (paramUsage) {
            case PATH:
                if (value == null) {
                    throw new IllegalArgumentException("Path parameter \"" + name + "\" value must not be null.");
                }
                addPathParam(name, value.toString());
                break;
            case ENCODED_PATH:
                if (value == null) {
                    throw new IllegalArgumentException("Path parameter \"" + name + "\" value must not be null.");
                }
                addEncodedPathParam(name, value.toString());
                break;
            case QUERY:
                if (value != null) { // Skip null values.
                    addQueryParam(name, value.toString());
                }
                break;
            case ENCODED_QUERY:
                if (value != null) { // Skip null values.
                    addEncodedQueryParam(name, value.toString());
                }
                break;
            case HEADER:
                if (value != null) { // Skip null values.
                    addHeader(name, value.toString());
                }
                break;
            case FIELD:
                if (value != null) { // Skip null values.
                    formBody.addField(name, value.toString());
                }
                break;
            case PART:
                if (value != null) { // Skip null values.
                    if (value instanceof TypedOutput) {
                        multipartBody.addPart(name, (TypedOutput) value);
                    } else if (value instanceof String) {
                        multipartBody.addPart(name, new TypedString((String) value));
                    } else {
                        multipartBody.addPart(name, converter.toBody(value));
                    }
                }
                break;
            case BODY:
                if (value == null) {
                    throw new IllegalArgumentException("Body parameter value must not be null.");
                }
                if (value instanceof TypedOutput) {
                    body = (TypedOutput) value;
                } else {
                    body = converter.toBody(value);
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown parameter usage: " + paramUsage);
        }
    }
}
 
Example #19
Source File: PostConverter.java    From wear-notify-for-reddit with Apache License 2.0 4 votes vote down vote up
@Override public TypedOutput toBody(Object object) {
    return mOriginalConverter.toBody(object);
}
 
Example #20
Source File: Request.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the request body or {@code null}.
 */
public TypedOutput getBody() {
    return body;
}
 
Example #21
Source File: MarkAsReadConverter.java    From wear-notify-for-reddit with Apache License 2.0 4 votes vote down vote up
@Override public TypedOutput toBody(Object object) {
    throw new UnsupportedOperationException();
}
 
Example #22
Source File: ApacheClient.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
TypedOutputEntity(TypedOutput typedOutput) {
    this.typedOutput = typedOutput;
    setContentType(typedOutput.mimeType());
}
 
Example #23
Source File: SignalFxConverter.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
  String string = (String) object;
  return new TypedString(string);
}
 
Example #24
Source File: ApiDefs.java    From spark-sdk-android with Apache License 2.0 4 votes vote down vote up
@Multipart
@PUT("/v1/devices/{deviceID}")
Response flashFile(@Path("deviceID") String deviceID,
                   @Part("file") TypedOutput file);
 
Example #25
Source File: GoogleAnalytics.java    From foam with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public TypedOutput toBody(Object output) {
    return new TypedString(output.toString());
}
 
Example #26
Source File: AtlasSSEConverter.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
  return null;
}
 
Example #27
Source File: ConfigBinResponseConverter.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
  RequestBody requestBody = (RequestBody) object;
  return new StringTypedOutput(requestBody);
}
 
Example #28
Source File: InfluxDbResponseConverterTest.java    From kayenta with Apache License 2.0 4 votes vote down vote up
private String asString(TypedOutput typedOutput) throws Exception {
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  typedOutput.writeTo(bytes);
  return new String(bytes.toByteArray());
}
 
Example #29
Source File: InfluxDbResponseConverter.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
  return null;
}
 
Example #30
Source File: PrometheusResponseConverter.java    From kayenta with Apache License 2.0 4 votes vote down vote up
@Override
public TypedOutput toBody(Object object) {
  return null;
}