Java Code Examples for com.squareup.okhttp.RequestBody#create()

The following examples show how to use com.squareup.okhttp.RequestBody#create() . 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: ApiClient.java    From nifi-api-client-java with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize the given Java object into request body according to the object's
 * class and the request Content-Type.
 *
 * @param obj The Java object
 * @param contentType The request Content-Type
 * @return The serialized request body
 * @throws ApiException If fail to serialize the given object
 */
public RequestBody serialize(Object obj, String contentType) throws ApiException {
    if (obj instanceof byte[]) {
        // Binary (byte array) body parameter support.
        return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
    } else if (obj instanceof File) {
        // File body parameter support.
        return RequestBody.create(MediaType.parse(contentType), (File) obj);
    } else if (isJsonMime(contentType)) {
        String content;
        if (obj != null) {
            content = json.serialize(obj);
        } else {
            content = null;
        }
        return RequestBody.create(MediaType.parse(contentType), content);
    } else {
        throw new ApiException("Content type \"" + contentType + "\" is not supported");
    }
}
 
Example 2
Source File: OkHttpClientHttpRequestFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
static Request buildRequest(HttpHeaders headers, byte[] content, URI uri, HttpMethod method)
		throws MalformedURLException {

	com.squareup.okhttp.MediaType contentType = getContentType(headers);
	RequestBody body = (content.length > 0 ||
			com.squareup.okhttp.internal.http.HttpMethod.requiresRequestBody(method.name()) ?
			RequestBody.create(contentType, content) : null);

	Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body);
	for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
		String headerName = entry.getKey();
		for (String headerValue : entry.getValue()) {
			builder.addHeader(headerName, headerValue);
		}
	}
	return builder.build();
}
 
Example 3
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postBytes(String url, byte[] bytes) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, bytes);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 4
Source File: Api.java    From materialup with Apache License 2.0 6 votes vote down vote up
public static RequestBody getSearchBody(String query, int page) {
    try {
        JSONObject object = new JSONObject();
        object.put("indexName", getSearchIndexName());
        object.put("params", "query=" + query + "&hitsPerPage=20&page=" + page);
        JSONArray array = new JSONArray();
        array.put(object);
        JSONObject body = new JSONObject();
        body.put("requests", array);


        return RequestBody.create(MediaType.parse("application/json;charset=utf-8"), body.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String b = "{\"requests\":[{\"indexName\":\"" + getSearchIndexName() + "\",\"params\":\"\"query=" + query + "&hitsPerPage=20&page=" + page + "\"}]}";
    return RequestBody.create(MediaType.parse("application/json;charset=utf-8"), b);
}
 
Example 5
Source File: OkHttpClientHttpRequest.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] content)
		throws IOException {

	MediaType contentType = getContentType(headers);
	RequestBody body = (content.length > 0 ? RequestBody.create(contentType, content) : null);

	URL url = this.uri.toURL();
	String methodName = this.method.name();
	Request.Builder builder = new Request.Builder().url(url).method(methodName, body);

	for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
		String headerName = entry.getKey();
		for (String headerValue : entry.getValue()) {
			builder.addHeader(headerName, headerValue);
		}
	}
	Request request = builder.build();

	return new OkHttpListenableFuture(this.client.newCall(request));
}
 
Example 6
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postString(String url, String json) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 7
Source File: OkHttpPostRequest.java    From meiShi with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestBody buildRequestBody()
{
    validParams();
    RequestBody requestBody = null;


    switch (type)
    {
        case TYPE_PARAMS:
            FormEncodingBuilder builder = new FormEncodingBuilder();
            addParams(builder, params);
            requestBody = builder.build();
            break;
        case TYPE_BYTES:
            requestBody = RequestBody.create(mediaType != null ? mediaType : MEDIA_TYPE_STREAM, bytes);
            break;
        case TYPE_FILE:
            requestBody = RequestBody.create(mediaType != null ? mediaType : MEDIA_TYPE_STREAM, file);
            break;
        case TYPE_STRING:
            requestBody = RequestBody.create(mediaType != null ? mediaType : MEDIA_TYPE_STRING, content);
            break;
    }
    return requestBody;
}
 
Example 8
Source File: ApiRequestBodyConverter.java    From NewsMe with Apache License 2.0 5 votes vote down vote up
@Override public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    try {
        gson.toJson(value, type, writer);
        writer.flush();
    } catch (IOException e) {
        throw new AssertionError(e); // Writing to Buffer does no I/O.
    }
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
 
Example 9
Source File: HttpTestPost.java    From wind-im with Apache License 2.0 5 votes vote down vote up
static String post(String url, String json) throws IOException {
	RequestBody body = RequestBody.create(JSON, json);
	Request request = new Request.Builder().url(url).post(body).build();
	Response response = client.newCall(request).execute();
	System.out.println("response = " + response.isSuccessful());
	if (response.isSuccessful()) {
		return response.body().string();
	} else {
		throw new IOException("Unexpected code " + response);
	}
}
 
Example 10
Source File: HttpTestPost.java    From openzaly with Apache License 2.0 5 votes vote down vote up
static String post(String url, String json) throws IOException {
	RequestBody body = RequestBody.create(JSON, json);
	Request request = new Request.Builder().url(url).post(body).build();
	Response response = client.newCall(request).execute();
	System.out.println("response = " + response.isSuccessful());
	if (response.isSuccessful()) {
		return response.body().string();
	} else {
		throw new IOException("Unexpected code " + response);
	}
}
 
Example 11
Source File: GetTokensByCodeTest.java    From oxd with Apache License 2.0 5 votes vote down vote up
private static Request buildRequest(String authorization, String oxdId, String userId, String userSecret, String state, String nonce, DevelopersApi client) {

        final String json = "{\"oxd_id\":\"" + oxdId + "\",\"username\":\"" + userId + "\",\"password\":\"" + userSecret
                + "\",\"state\":\"" + state + "\",\"nonce\":\"" + nonce + "\"}";

        final RequestBody reqBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

        return new Request.Builder()
                .addHeader("Authorization", authorization)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .method("POST", reqBody)
                .url(client.getApiClient().getBasePath() + AUTH_CODE_ENDPOINT).build();

    }
 
Example 12
Source File: ToStringConverterFactory.java    From materialup with Apache License 2.0 5 votes vote down vote up
@Override
public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
    if (String.class.equals(type)) {
        return new Converter<String, RequestBody>() {
            @Override
            public RequestBody convert(String value) throws IOException {
                return RequestBody.create(MEDIA_TYPE, value);
            }
        };
    }
    return null;
}
 
Example 13
Source File: HttpTestPost.java    From openzaly with Apache License 2.0 5 votes vote down vote up
static String post(String url, String json) throws IOException {
	RequestBody body = RequestBody.create(JSON, json);
	Request request = new Request.Builder().url(url).post(body).build();
	Response response = client.newCall(request).execute();
	System.out.println("response = " + response.isSuccessful());
	if (response.isSuccessful()) {
		return response.body().string();
	} else {
		throw new IOException("Unexpected code " + response);
	}
}
 
Example 14
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Create a user if the user does not already exist.</br>
 * <b>URL</b>: /users</br>
 * <b>Method</b>: POST
 *
 * @param user
 *            [required] (New created user)
 * @return
 * @throws IOException
 */
public HarborResponse createUser(ProjectMember user) throws IOException {
	HarborResponse result = new HarborResponse();
	String res;
	String url = baseUrl + "users";
	RequestBody requestBody = RequestBody.create(JSON, mapper.writeValueAsString(user));
	Request request = new Request.Builder().url(url).post(requestBody).build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	switch (response.code()) {
	case 201:
		res = "User created successfully.";
		break;
	case 400:
		res = "Unsatisfied with constraints of the user creation.";
		break;
	case 403:
		res = "User registration can only be used by admin role user when self-registration is off.";
		break;
	case 409:
		res = "username has already been used.";
		break;
	case 500:
		res = "Unexpected internal errors.";
		break;
	default:
		res = "Unknown.";
		break;
	}
	result.setCode(Integer.toString(response.code()));
	result.setMessage(res);
	return result;
}
 
Example 15
Source File: StethoInterceptorTest.java    From stetho with MIT License 5 votes vote down vote up
@Test
public void testWithRequestCompression() throws IOException {
  AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest =
      hookAlmostRealRequestWillBeSent(mMockEventReporter);

  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse()
      .setBody("Success!"));

  final byte[] decompressed = "Request text".getBytes();
  final byte[] compressed = compress(decompressed);
  assertNotEquals(
      "Bogus test: decompressed and compressed lengths match",
      compressed.length, decompressed.length);

  RequestBody compressedBody = RequestBody.create(
      MediaType.parse("text/plain"),
      compress(decompressed));
  Request request = new Request.Builder()
      .url(server.getUrl("/"))
      .addHeader("Content-Encoding", "gzip")
      .post(compressedBody)
      .build();
  Response response = mClientWithInterceptor.newCall(request).execute();

  // Force a read to complete the flow.
  response.body().string();

  assertArrayEquals(decompressed, capturedRequest.get().body());
  Mockito.verify(mMockEventReporter)
      .dataSent(
          anyString(),
          eq(decompressed.length),
          eq(compressed.length));

  server.shutdown();
}
 
Example 16
Source File: JacksonConverterFactory.java    From mattermost-android-classic with Apache License 2.0 4 votes vote down vote up
@Override
public RequestBody convert(T value) throws IOException {
    byte[] bytes = adapter.writeValueAsBytes(value);
    return RequestBody.create(MEDIA_TYPE, bytes);
}
 
Example 17
Source File: PostFileRequest.java    From NewsMe with Apache License 2.0 4 votes vote down vote up
@Override
protected RequestBody buildRequestBody()
{
    return RequestBody.create(mediaType, file);
}
 
Example 18
Source File: Ok2Factory.java    From httplite with Apache License 2.0 4 votes vote down vote up
@Override
public RequestBody createRequestBody(String content, String mediaType) {
    return RequestBody.create(MediaType.parse(mediaType), content);
}
 
Example 19
Source File: OkHttpStack.java    From SimplifyReader with Apache License 2.0 4 votes vote down vote up
private static RequestBody createRequestBody(Request r) throws AuthFailureError {
    final byte[] body = r.getBody();
    if (body == null) return null;

    return RequestBody.create(MediaType.parse(r.getBodyContentType()), body);
}
 
Example 20
Source File: ApiClient.java    From nifi-api-client-java with Apache License 2.0 4 votes vote down vote up
/**
 * Build HTTP call with the given options.
 *
 * @param path The sub-path of the HTTP URL
 * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
 * @param queryParams The query parameters
 * @param body The request body object
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param authNames The authentications to apply
 * @param progressRequestListener Progress request listener
 * @return The HTTP call
 * @throws ApiException If fail to serialize the request body object
 */
public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    updateParamsForAuth(authNames, queryParams, headerParams);

    final String url = buildUrl(path, queryParams);
    final Request.Builder reqBuilder = new Request.Builder().url(url);
    processHeaderParams(headerParams, reqBuilder);

    String contentType = (String) headerParams.get("Content-Type");
    // ensuring a default content type
    if (contentType == null) {
        contentType = "application/json";
    }

    RequestBody reqBody;
    if (!HttpMethod.permitsRequestBody(method)) {
        reqBody = null;
    } else if ("application/x-www-form-urlencoded".equals(contentType)) {
        reqBody = buildRequestBodyFormEncoding(formParams);
    } else if ("multipart/form-data".equals(contentType)) {
        reqBody = buildRequestBodyMultipart(formParams);
    } else if (body == null) {
        if ("DELETE".equals(method)) {
            // allow calling DELETE without sending a request body
            reqBody = null;
        } else {
            // use an empty request body (for POST, PUT and PATCH)
            reqBody = RequestBody.create(MediaType.parse(contentType), "");
        }
    } else {
        reqBody = serialize(body, contentType);
    }

    Request request = null;

    if(progressRequestListener != null && reqBody != null) {
        ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
        request = reqBuilder.method(method, progressRequestBody).build();
    } else {
        request = reqBuilder.method(method, reqBody).build();
    }

    return httpClient.newCall(request);
}