List of usage examples for com.squareup.okhttp Request.Builder method
String method
To view the source code for com.squareup.okhttp Request.Builder method.
Click Source Link
From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java
License:Apache License
public Response doRest(String path, String requestBody, HttpVerb verb) throws IOException, RestApiException { OkHttpClient client = new OkHttpClient(); Optional<String> gerritAuthOptional = updateGerritAuthWhenRequired(client); String uri = authData.getHost(); // only use /a when http login is required (i.e. we haven't got a gerrit-auth cookie) // it would work in most cases also with /a, but it breaks with HTTP digest auth ("Forbidden" returned) if (authData.isLoginAndPasswordAvailable() && !gerritAuthOptional.isPresent()) { uri += "/a"; }/* w w w .j av a 2 s . co m*/ uri += path; Request.Builder builder = new Request.Builder().url(uri).addHeader("Accept", MEDIA_TYPE_JSON.toString()); if (verb == HttpVerb.GET) { builder = builder.get(); } else if (verb == HttpVerb.DELETE) { builder = builder.delete(); } else { if (requestBody == null) { builder.method(verb.toString(), null); } else { builder.method(verb.toString(), RequestBody.create(MEDIA_TYPE_JSON, requestBody)); } } if (gerritAuthOptional.isPresent()) { builder.addHeader("X-Gerrit-Auth", gerritAuthOptional.get()); } return httpRequestExecutor.execute(client, builder); }
From source file:de.feike.tiingoclient.ApiClient.java
License:Apache License
/** * Build HTTP call with the given options. * * @param path// w w w.ja va 2s . c om * 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 { 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); }
From source file:feign.okhttp.OkHttpClient.java
License:Apache License
static Request toOkHttpRequest(feign.Request input) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(input.url());// www . j a v a 2 s.c om MediaType mediaType = null; boolean hasAcceptHeader = false; for (String field : input.headers().keySet()) { if (field.equalsIgnoreCase("Accept")) { hasAcceptHeader = true; } for (String value : input.headers().get(field)) { if (field.equalsIgnoreCase("Content-Type")) { mediaType = MediaType.parse(value); if (input.charset() != null) { mediaType.charset(input.charset()); } } else { requestBuilder.addHeader(field, value); } } } // Some servers choke on the default accept string. if (!hasAcceptHeader) { requestBuilder.addHeader("Accept", "*/*"); } RequestBody body = input.body() != null ? RequestBody.create(mediaType, input.body()) : null; requestBuilder.method(input.method(), body); return requestBuilder.build(); }
From source file:io.minio.MinioClient.java
License:Apache License
/** * Creates Request object for given request parameters. * * @param method HTTP method.// www. j a v a2s .c o m * @param bucketName Bucket name. * @param objectName Object name in the bucket. * @param region Amazon S3 region of the bucket. * @param headerMap Map of HTTP headers for the request. * @param queryParamMap Map of HTTP query parameters of the request. * @param contentType Content type of the request body. * @param body HTTP request body. * @param length Length of HTTP request body. */ private Request createRequest(Method method, String bucketName, String objectName, String region, Map<String, String> headerMap, Map<String, String> queryParamMap, final String contentType, final Object body, final int length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException { if (bucketName == null && objectName != null) { throw new InvalidBucketNameException(NULL_STRING, "null bucket name for object '" + objectName + "'"); } HttpUrl.Builder urlBuilder = this.baseUrl.newBuilder(); if (bucketName != null) { checkBucketName(bucketName); String host = this.baseUrl.host(); if (host.equals(S3_AMAZONAWS_COM)) { // special case: handle s3.amazonaws.com separately if (region != null) { host = AwsS3Endpoints.INSTANCE.endpoint(region); } boolean usePathStyle = false; if (method == Method.PUT && objectName == null && queryParamMap == null) { // use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from s3.amazonaws.com usePathStyle = true; } else if (queryParamMap != null && queryParamMap.containsKey("location")) { // use path style for location query usePathStyle = true; } else if (bucketName.contains(".") && this.baseUrl.isHttps()) { // use path style where '.' in bucketName causes SSL certificate validation error usePathStyle = true; } if (usePathStyle) { urlBuilder.host(host); urlBuilder.addPathSegment(bucketName); } else { urlBuilder.host(bucketName + "." + host); } } else { urlBuilder.addPathSegment(bucketName); } } if (objectName != null) { for (String pathSegment : objectName.split("/")) { // Limitation: // 1. OkHttp does not allow to add '.' and '..' as path segment. // 2. Its not allowed to add path segment as '/', '//', '/usr' or 'usr/'. urlBuilder.addPathSegment(pathSegment); } } if (queryParamMap != null) { for (Map.Entry<String, String> entry : queryParamMap.entrySet()) { urlBuilder.addEncodedQueryParameter(Signer.encodeQueryString(entry.getKey()), Signer.encodeQueryString(entry.getValue())); } } RequestBody requestBody = null; if (body != null) { requestBody = new RequestBody() { @Override public MediaType contentType() { if (contentType != null) { return MediaType.parse(contentType); } else { return MediaType.parse("application/octet-stream"); } } @Override public long contentLength() { if (body instanceof InputStream || body instanceof RandomAccessFile || body instanceof byte[]) { return length; } if (length == 0) { return -1; } else { return length; } } @Override public void writeTo(BufferedSink sink) throws IOException { byte[] data = null; if (body instanceof InputStream) { InputStream stream = (InputStream) body; sink.write(Okio.source(stream), length); } else if (body instanceof RandomAccessFile) { RandomAccessFile file = (RandomAccessFile) body; sink.write(Okio.source(Channels.newInputStream(file.getChannel())), length); } else if (body instanceof byte[]) { sink.write(data, 0, length); } else { sink.writeUtf8(body.toString()); } } }; } HttpUrl url = urlBuilder.build(); // urlBuilder does not encode some characters properly for Amazon S3. // Encode such characters properly here. List<String> pathSegments = url.encodedPathSegments(); urlBuilder = url.newBuilder(); for (int i = 0; i < pathSegments.size(); i++) { urlBuilder.setEncodedPathSegment(i, pathSegments.get(i).replaceAll("\\!", "%21").replaceAll("\\$", "%24").replaceAll("\\&", "%26") .replaceAll("\\'", "%27").replaceAll("\\(", "%28").replaceAll("\\)", "%29") .replaceAll("\\*", "%2A").replaceAll("\\+", "%2B").replaceAll("\\,", "%2C") .replaceAll("\\:", "%3A").replaceAll("\\;", "%3B").replaceAll("\\=", "%3D") .replaceAll("\\@", "%40").replaceAll("\\[", "%5B").replaceAll("\\]", "%5D")); } url = urlBuilder.build(); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); requestBuilder.method(method.toString(), requestBody); if (headerMap != null) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { requestBuilder.header(entry.getKey(), entry.getValue()); } } String sha256Hash = null; String md5Hash = null; if (this.accessKey != null && this.secretKey != null) { // No need to compute sha256 if endpoint scheme is HTTPS. Issue #415. if (url.isHttps()) { sha256Hash = "UNSIGNED-PAYLOAD"; if (body instanceof BufferedInputStream) { md5Hash = Digest.md5Hash((BufferedInputStream) body, length); } else if (body instanceof RandomAccessFile) { md5Hash = Digest.md5Hash((RandomAccessFile) body, length); } else if (body instanceof byte[]) { byte[] data = (byte[]) body; md5Hash = Digest.md5Hash(data, length); } } else { if (body == null) { sha256Hash = Digest.sha256Hash(new byte[0]); } else { if (body instanceof BufferedInputStream) { String[] hashes = Digest.sha256md5Hashes((BufferedInputStream) body, length); sha256Hash = hashes[0]; md5Hash = hashes[1]; } else if (body instanceof RandomAccessFile) { String[] hashes = Digest.sha256md5Hashes((RandomAccessFile) body, length); sha256Hash = hashes[0]; md5Hash = hashes[1]; } else if (body instanceof byte[]) { byte[] data = (byte[]) body; sha256Hash = Digest.sha256Hash(data, length); md5Hash = Digest.md5Hash(data, length); } else { sha256Hash = Digest.sha256Hash(body.toString()); } } } } if (md5Hash != null) { requestBuilder.header("Content-MD5", md5Hash); } if (url.port() == 80 || url.port() == 443) { requestBuilder.header("Host", url.host()); } else { requestBuilder.header("Host", url.host() + ":" + url.port()); } requestBuilder.header("User-Agent", this.userAgent); if (sha256Hash != null) { requestBuilder.header("x-amz-content-sha256", sha256Hash); } DateTime date = new DateTime(); requestBuilder.header("x-amz-date", date.toString(DateFormat.AMZ_DATE_FORMAT)); return requestBuilder.build(); }
From source file:it.smartcommunitylab.ApiClient.java
License:Apache License
/** * Build an HTTP request 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 collectionQueryParams The collection query parameters * @param body The request body object/*from w ww . ja v a 2 s . c om*/ * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP request * @throws ApiException If fail to serialize the request body object */ public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, 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, collectionQueryParams); 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 request; }
From source file:nextflow.ga4gh.tes.client.ApiClient.java
License:Apache License
/** * Build an HTTP request 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//from w w w. jav a 2 s.c om * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP request * @throws ApiException If fail to serialize the request body object */ public Request buildRequest(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 request; }
From source file:org.apache.nifi.processors.standard.InvokeHTTP.java
License:Apache License
private Request configureRequest(final ProcessContext context, final ProcessSession session, final FlowFile requestFlowFile, URL url) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder = requestBuilder.url(url); final String authUser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).getValue()); // If the username/password properties are set then check if digest auth is being used if (!authUser.isEmpty() && "false".equalsIgnoreCase(context.getProperty(PROP_DIGEST_AUTH).getValue())) { final String authPass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).getValue()); String credential = com.squareup.okhttp.Credentials.basic(authUser, authPass); requestBuilder = requestBuilder.header("Authorization", credential); }//from ww w .j a v a 2 s .c o m // set the request method String method = trimToEmpty( context.getProperty(PROP_METHOD).evaluateAttributeExpressions(requestFlowFile).getValue()) .toUpperCase(); switch (method) { case "GET": requestBuilder = requestBuilder.get(); break; case "POST": RequestBody requestBody = getRequestBodyToSend(session, context, requestFlowFile); requestBuilder = requestBuilder.post(requestBody); break; case "PUT": requestBody = getRequestBodyToSend(session, context, requestFlowFile); requestBuilder = requestBuilder.put(requestBody); break; case "PATCH": requestBody = getRequestBodyToSend(session, context, requestFlowFile); requestBuilder = requestBuilder.patch(requestBody); break; case "HEAD": requestBuilder = requestBuilder.head(); break; case "DELETE": requestBuilder = requestBuilder.delete(); break; default: requestBuilder = requestBuilder.method(method, null); } requestBuilder = setHeaderProperties(context, requestBuilder, requestFlowFile); return requestBuilder.build(); }
From source file:org.mariotaku.twidere.util.net.OkHttpRestClient.java
License:Open Source License
@NonNull @Override//from w ww . j a va 2 s. c om public RestHttpResponse execute(RestHttpRequest restHttpRequest) throws IOException { final Request.Builder builder = new Request.Builder(); builder.method(restHttpRequest.getMethod(), RestToOkBody.wrap(restHttpRequest.getBody())); builder.url(restHttpRequest.getUrl()); final List<Pair<String, String>> headers = restHttpRequest.getHeaders(); if (headers != null) { for (Pair<String, String> header : headers) { builder.addHeader(header.first, header.second); } } final Call call = client.newCall(builder.build()); return new OkRestHttpResponse(call.execute()); }
From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java
private Response getConnection(String urlFragment, String method, String body) throws PushNetworkException { try {//from w w w . ja v a2 s. c o m Log.w(TAG, "Push service URL: " + serviceUrl); Log.w(TAG, "Opening URL: " + String.format("%s%s", serviceUrl, urlFragment)); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, null); OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setSslSocketFactory(context.getSocketFactory()); okHttpClient.setHostnameVerifier(new StrictHostnameVerifier()); Request.Builder request = new Request.Builder(); request.url(String.format("%s%s", serviceUrl, urlFragment)); if (body != null) { request.method(method, RequestBody.create(MediaType.parse("application/json"), body)); } else { request.method(method, null); } if (credentialsProvider.getPassword() != null) { request.addHeader("Authorization", getAuthorizationHeader()); } if (userAgent != null) { request.addHeader("X-Signal-Agent", userAgent); } return okHttpClient.newCall(request.build()).execute(); } catch (IOException e) { throw new PushNetworkException(e); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new AssertionError(e); } }
From source file:windows.webservices.utilidades.EjecutorJson.java
private Request prepararRequest() { Request.Builder build; if ((json == null || json.isEmpty()) && metodosDeEnvio.equals(MetodosDeEnvio.POST) && param != null) { json = "recibir datos por query param"; }//w w w.j a v a2 s . c om if (json != null && !json.equals("")) { build = new Request.Builder().url(uri.toString()); RequestBody body = RequestBody.create(com.squareup.okhttp.MediaType.parse(MediaType.APPLICATION_JSON), json); build.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON).addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); switch (metodosDeEnvio) { case POST: prepararParam(); build.url(uri.toString()).post(body); break; case GET: build.method(metodosDeEnvio.getMetodo(), body); break; case PUT: prepararParam(); build.url(uri.toString()).put(body); break; case DELETE: prepararParam(); build.url(uri.toString()).delete(body); break; } } else { prepararParam(); build = new Request.Builder().url(uri.toString()); build.method(metodosDeEnvio.getMetodo(), null); } return build.build(); }