Java Code Examples for com.squareup.okhttp.RequestBody

The following examples show how to use com.squareup.okhttp.RequestBody. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: wind-im   Source File: ZalyHttpClient.java    License: 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 2
Source Project: openzaly   Source File: ZalyHttpClient.java    License: 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 3
Source Project: tencentcloud-sdk-java   Source File: HttpConnection.java    License: Apache License 2.0 6 votes vote down vote up
public Response postRequest(String url, String body, Headers headers)
    throws TencentCloudSDKException {
  MediaType contentType = MediaType.parse(headers.get("Content-Type"));
  Request request = null;
  try {
    request =
        new Request.Builder()
            .url(url)
            .post(RequestBody.create(contentType, body))
            .headers(headers)
            .build();
  } catch (IllegalArgumentException e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }

  return this.doRequest(request);
}
 
Example 4
Source Project: tencentcloud-sdk-java   Source File: HttpConnection.java    License: Apache License 2.0 6 votes vote down vote up
public Response postRequest(String url, byte[] body, Headers headers)
    throws TencentCloudSDKException {
  MediaType contentType = MediaType.parse(headers.get("Content-Type"));
  Request request = null;
  try {
    request =
        new Request.Builder()
            .url(url)
            .post(RequestBody.create(contentType, body))
            .headers(headers)
            .build();
  } catch (IllegalArgumentException e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }

  return this.doRequest(request);
}
 
Example 5
Source Project: openzaly   Source File: ZalyHttpClient.java    License: 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 6
Source Project: meiShi   Source File: OkHttpPostRequest.java    License: 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 7
Source Project: harbor-java-client   Source File: HarborClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Let user search access logs filtered by operations and date time
 * ranges.</br>
 * <b>URL</b>: /projects/{project_id}/logs/filter</br>
 * <b>Method</b>: POST
 *
 * @param projectId
 *            [required] (Selected project ID)
 * @param accessLog
 *            (Search results of access logs)
 * @return
 * @throws HarborClientException
 * @throws IOException
 */

public List<Log> filterLog(int projectId, Log accessLog) throws HarborClientException, IOException {
	List<Log> res = new ArrayList<>();
	String url = baseUrl + "projects/" + projectId + "/logs/filter";
	RequestBody requestBody = RequestBody.create(JSON, mapper.writeValueAsString(accessLog));
	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 200:
		res = mapper.readValue(response.body().string(), new TypeReference<List<Log>>() {
		});
		break;
	case 400:
		throw new HarborClientException(String.valueOf(response.code()), "Illegal format of provided ID value.");
	case 401:
		throw new HarborClientException(String.valueOf(response.code()), "User need to log in first.");
	case 500:
		throw new HarborClientException(String.valueOf(response.code()), "Unexpected internal errors.");
	default:
		throw new HarborClientException(String.valueOf(response.code()), "Unknown.");
	}
	return res;
}
 
Example 8
Source Project: find-client-android   Source File: FindWiFiImpl.java    License: MIT License 6 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {

    try {
        Request.Builder requestBuilder = new Request.Builder()
                .url(serverAddr + urlPart);
        switch (method) {
            case PUT:
                requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            case POST:
                requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            case DELETE:
                requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            default: break;
        }
        Request request = requestBuilder.build();
        httpClient.newCall(request).enqueue(new HttpCallback(callback));
    } catch (Exception e) {
        Log.e(TAG, "IOException", e);
    }
    return null;
}
 
Example 9
Source Project: meiShi   Source File: OkHttpPostRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final ResultCallback callback)
{
    CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
    {
        @Override
        public void onRequestProgress(final long bytesWritten, final long contentLength)
        {

            mOkHttpClientManager.getDelivery().post(new Runnable()
            {
                @Override
                public void run()
                {
                    callback.inProgress(bytesWritten * 1.0f / contentLength);
                }
            });

        }
    });
    return countingRequestBody;
}
 
Example 10
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 11
@Override
protected Void doInBackground(Void... params) {

    RequestBody requestBody = new FormEncodingBuilder()
            .add("grant_type", "authorization_code")
            .add("client_id", mClientId)
            .add("client_secret", "ADD_YOUR_CLIENT_SECRET")
            .add("redirect_uri","")
            .add("code", mCode)
            .build();
    final Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    mOkHttpClient.newCall(request).enqueue(new HttpCallback(mCallBack));
    return null;
}
 
Example 12
Source Project: NewsMe   Source File: PostFormRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
    if (callback == null) return requestBody;
    CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
    {
        @Override
        public void onRequestProgress(final long bytesWritten, final long contentLength)
        {

            OkHttpUtils.getInstance().getDelivery().post(new Runnable()
            {
                @Override
                public void run()
                {
                    callback.inProgress(bytesWritten * 1.0f / contentLength);
                }
            });

        }
    });
    return countingRequestBody;
}
 
Example 13
Source Project: meiShi   Source File: OkHttpUploadRequest.java    License: Apache License 2.0 6 votes vote down vote up
private void addParams(MultipartBuilder builder, Map<String, String> params)
{
    if (builder == null)
    {
        throw new IllegalArgumentException("builder can not be null .");
    }

    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));

        }
    }
}
 
Example 14
Source Project: find-client-android   Source File: FindWiFiImpl.java    License: MIT License 6 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {

    try {
        Request.Builder requestBuilder = new Request.Builder()
                .url(serverAddr + urlPart);
        switch (method) {
            case PUT:
                requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            case POST:
                requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            case DELETE:
                requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            default: break;
        }
        Request request = requestBuilder.build();
        httpClient.newCall(request).enqueue(new HttpCallback(callback));
    } catch (Exception e) {
        Log.e(TAG, "IOException", e);
    }
    return null;
}
 
Example 15
Source Project: nifi-api-client-java   Source File: ApiClient.java    License: 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 16
Source Project: Pas   Source File: DOkHttp.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 上传文件
 * 也可以和数据post一起提交 监听progress
 * @param requestBody
 * @param uIchangeListener
 */
public void uploadPost2ServerProgress(Context context,String url, RequestBody requestBody,
                                      MyCallBack myCallBack, final UIchangeListener uIchangeListener){

    ProgressRequestBody progressRequestBody=ProgressHelper.addProgressRequestListener(requestBody, new UIProgressRequestListener() {
        @Override
        public void onUIRequestProgress(long bytesWrite, long contentLength, boolean done) {
            uIchangeListener.progressUpdate(bytesWrite,contentLength,done);
        }
    });

    Request request=new Request.Builder()
            .tag(context)
            .post(progressRequestBody)
            .url(url)
            .build();

    postData2Server(request,myCallBack);

}
 
Example 17
Source Project: xDrip   Source File: SendFeedBack.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * https://github.com/square/okhttp/issues/350
 */
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}
 
Example 18
Source Project: xDrip-plus   Source File: SendFeedBack.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * https://github.com/square/okhttp/issues/350
 */
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}
 
Example 19
Source Project: xDrip-plus   Source File: SendFeedBack.java    License: GNU General Public License v3.0 6 votes vote down vote up
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            return -1; // We don't know the compressed length in advance!
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
 
Example 20
Source Project: stetho   Source File: StethoInterceptorTest.java    License: 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 21
Source Project: yahnac   Source File: ConnectionProvider.java    License: Apache License 2.0 5 votes vote down vote up
public Request commentOnStoryRequest(String itemId, String comment, String hmac) {
    RequestBody requestBody = (new FormEncodingBuilder())
            .add("parent", itemId)
            .add("goto", (new StringBuilder()).append("item?id=").append(itemId).toString())
            .add("text", comment)
            .add("hmac", hmac)
            .build();

    return createAuthRequest(requestBody);
}
 
Example 22
Source Project: openzaly   Source File: HttpClient.java    License: Apache License 2.0 5 votes vote down vote up
static String postKV(String url) throws IOException {

		RequestBody formBody = new FormEncodingBuilder().add("platform", "android").add("name", "bug").build();

		Request request = new Request.Builder().url(url).post(formBody).build();

		Response response = client.newCall(request).execute();
		System.out.println("post KV response =" + response.isSuccessful());
		if (response.isSuccessful()) {
			return response.body().string();
		} else {
			throw new IOException("Unexpected code " + response);
		}
	}
 
Example 23
Source Project: openzaly   Source File: HttpTestPost.java    License: 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 24
Source Project: yahnac   Source File: ConnectionProvider.java    License: Apache License 2.0 5 votes vote down vote up
private Request createAuthRequest(RequestBody requestBody) {
    return (new Request.Builder())
            .addHeader("cookie", (new StringBuilder()).append("user=").append(loginSharedPreferences.getCookie()).toString())
            .url(ConnectionProvider.BASE_URL + ConnectionProvider.SEND_COMMENT_BASE_URL)
            .post(requestBody)
            .build();
}
 
Example 25
Source Project: xpay   Source File: RequestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String post(String url, String json){
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    try {
        Response response = client.newCall(request).execute();
        return response.body().string();
    } catch (IOException e) {
        Log.e("ZYKJ",e.getMessage());
    }
    return "";
}
 
Example 26
Source Project: Mizuu   Source File: MizLib.java    License: Apache License 2.0 5 votes vote down vote up
public static Request getJsonPostRequest(String url, JSONObject holder) {
    return new Request.Builder()
            .url(url)
            .addHeader("Content-type", "application/json")
            .post(RequestBody.create(MediaType.parse("application/json"), holder.toString()))
            .build();
}
 
Example 27
Source Project: openzaly   Source File: HttpTestPost.java    License: 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 28
Source Project: lunzi   Source File: UploadFileRequest.java    License: Apache License 2.0 5 votes vote down vote up
private void newRequestCall(Callback callback, String url, RequestBody requestBody) {
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(callback);
}
 
Example 29
Source Project: swaggerhub-gradle-plugin   Source File: SwaggerHubClient.java    License: Apache License 2.0 5 votes vote down vote up
private Request buildPostRequest(HttpUrl httpUrl, MediaType mediaType, String content) {
    return new Request.Builder()
            .url(httpUrl)
            .addHeader("Content-Type", mediaType.toString())
            .addHeader("Authorization", token)
            .addHeader("User-Agent", "swaggerhub-gradle-plugin")
            .post(RequestBody.create(mediaType, content))
            .build();
}
 
Example 30
Source Project: harbor-java-client   Source File: HarborClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * For user to create a new project.</br>
 * <b>URL</b>: /projects</br>
 * <b>Method</b>: POST
 *
 * @param project
 *            [required] (New created project)
 * @return
 * @throws IOException
 */

public HarborResponse createProject(Project project) throws IOException {
	HarborResponse result = new HarborResponse();
	String res;
	String url = baseUrl + "projects";
	RequestBody requestBody = RequestBody.create(JSON, mapper.writeValueAsString(project));
	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 = "Project created successfully.";
		break;
	case 400:
		res = "Unsatisfied with constraints of the project creation.";
		break;
	case 401:
		res = "User need to log in first.";
		break;
	case 409:
		res = "Project name already exists.";
		break;
	case 500:
		res = "Unexpected internal errors.";
		break;
	default:
		res = "Unknown.";
		break;
	}
	result.setCode(Integer.toString(response.code()));
	result.setMessage(res);
	return result;
}