com.squareup.okhttp.RequestBody Java Examples

The following examples show how to use com.squareup.okhttp.RequestBody. 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: DOkHttp.java    From Pas with Apache License 2.0 7 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 #2
Source File: FindWiFiImpl.java    From find-client-android with 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 #3
Source File: OkHttpUploadRequest.java    From meiShi with 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 #4
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 #5
Source File: SendFeedBack.java    From xDrip with 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 #6
Source File: SendFeedBack.java    From xDrip-plus with 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 #7
Source File: SendFeedBack.java    From xDrip-plus with 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 #8
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 #9
Source File: FindWiFiImpl.java    From find-client-android with 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 #10
Source File: HttpConnection.java    From tencentcloud-sdk-java with 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 #11
Source File: PostFormRequest.java    From NewsMe with 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 #12
Source File: HttpConnection.java    From tencentcloud-sdk-java with 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 #13
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 #14
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 #15
Source File: RequestAccessTokenTask.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #16
Source File: HarborClient.java    From harbor-java-client with 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 #17
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 #18
Source File: OkHttpPostRequest.java    From meiShi with 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 #19
Source File: ZalyHttpClient.java    From wind-im 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 #20
Source File: Ok2Factory.java    From httplite with Apache License 2.0 5 votes vote down vote up
private RequestBody convertBody(alexclin.httplite.RequestBody requestBody, String mediaType, ProgressListener listener) {
    if (requestBody == null) return null;
    if (requestBody instanceof alexclin.httplite.RequestBody.NotBody) {
        RequestBody body = ((alexclin.httplite.RequestBody.NotBody) requestBody).createReal(this);
        return new ProgressRequestBody(body, mediaType, listener);
    } else {
        return new Ok2RequestBody(requestBody, mediaType, listener);
    }
}
 
Example #21
Source File: OkHttpStack.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example #22
Source File: JsonRequestBodyBuilder.java    From Auth0.Android with MIT License 5 votes vote down vote up
public static RequestBody createBody(Object pojo, Gson gson) throws RequestBodyBuildException {
    try {
        return RequestBody.create(JSON, gson.toJson(pojo));
    } catch (Exception e) {
        throw new RequestBodyBuildException("Failed to convert " + pojo.getClass().getName() + " to JSON", e);
    }
}
 
Example #23
Source File: TransactionsFragment.java    From utexas-utilities with Apache License 2.0 5 votes vote down vote up
public LoadSucceededEvent(String tag, List<Transaction> transactions, String balance,
                          boolean morePagesAvailable, RequestBody form) {
    this.tag = tag;
    this.transactions = transactions;
    this.balance = balance;
    this.morePagesAvailable = morePagesAvailable;
    this.form = form;
}
 
Example #24
Source File: OkHttpStack.java    From wasp with Apache License 2.0 5 votes vote down vote up
private static RequestBody createRequestBody(Request request) throws AuthFailureError {
  byte[] body = request.getBody();
  if (body == null) {
    return null;
  }
  return RequestBody.create(MediaType.parse(request.getBodyContentType()), body);
}
 
Example #25
Source File: TweetPublishPresenter.java    From FlowGeek with GNU General Public License v2.0 5 votes vote down vote up
public void publishTweet(long uid, String message, File image, File voice){
    RequestBody _uid = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(uid));
    RequestBody _message = RequestBody.create(MediaType.parse("multipart/form-data"), message);
    RequestBody _image = image == null
            ? null
            : RequestBody.create(MediaType.parse("multipart/form-data"), image);
    RequestBody _voice = voice == null
            ? null
            : RequestBody.create(MediaType.parse("multipart/form-data"), voice);

    Log.d("thanatosx", String.format("uid=%d, message=%s, image=%s, voice=%s", uid, message, image, voice));

    Call<RespResult> Call = ServerAPI.getOSChinaAPI().publicTweet(_uid, _message, _image, _voice);
    Call.enqueue(new Callback<RespResult>() {
        @Override
        public void onResponse(Response<RespResult> response, Retrofit retrofit) {
            RespResult result = response.body();
            if (result.getResult().getErrorCode() == 1){
                Toast.makeText(AppManager.context, "发表成功", Toast.LENGTH_SHORT)
                        .show();
            }else{
                Toast.makeText(AppManager.context,
                        result.getResult().getErrorMessage(), Toast.LENGTH_SHORT)
                        .show();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
            Toast.makeText(AppManager.context, "发送失败", Toast.LENGTH_SHORT).show();
        }
    });
}
 
Example #26
Source File: HawkularMetricsClient.java    From apiman with Apache License 2.0 5 votes vote down vote up
private static RequestBody toBody(Object bean) {
    try {
        RequestBody body = RequestBody.create(JSON, writeMapper.writeValueAsString(bean));
        return body;
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: AuthCookie.java    From utexas-utilities with Apache License 2.0 5 votes vote down vote up
protected Request buildLoginRequest() {
    String user = settings.getString("eid", "error");
    String pw = UTilitiesApplication.getInstance().getSecurePreferences()
            .getString("password", "error");

    RequestBody requestBody = new FormEncodingBuilder()
            .add(userNameKey, user)
            .add(passwordKey, pw)
            .build();
    return new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
}
 
Example #28
Source File: UploadFileRequest.java    From lunzi with Apache License 2.0 5 votes vote down vote up
public static RequestBody createCustomRequestBody(final MediaType contentType, final File file, final UploadCallback listener) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return contentType;
        }

        @Override
        public long contentLength() {
            return file.length();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source;
            try {
                source = Okio.source(file);
                //sink.writeAll(source);
                Buffer buf = new Buffer();
                Long remaining = contentLength();
                for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                    sink.write(buf, readCount);
                    listener.onProgress(contentLength(), remaining -= readCount, remaining == 0);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
 
Example #29
Source File: SwaggerHubClient.java    From swaggerhub-maven-plugin with Apache License 2.0 5 votes vote down vote up
private Request buildPutRequest(HttpUrl httpUrl, MediaType mediaType, String content) {
    return new Request.Builder()
            .url(httpUrl)
            .addHeader("Content-Type", mediaType.toString())
            .addHeader("Authorization", token)
            .addHeader("User-Agent", "swaggerhub-maven-plugin")
            .put(RequestBody.create(mediaType, content))
            .build();
}
 
Example #30
Source File: ToStringConverter.java    From WeGit 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;
}