okhttp3.Request.Builder Java Examples

The following examples show how to use okhttp3.Request.Builder. 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: HttpClient.java    From zbus-server with MIT License 6 votes vote down vote up
static Request trans(Message msg){
	Builder builder = new Builder();
	HttpUrl url = HttpUrl.parse(msg.getUrl());
	builder.url(url);
	for(Entry<String, String> e : msg.getHeaders().entrySet()){
		builder.addHeader(e.getKey(), e.getValue());
	}
	if("GET".equalsIgnoreCase(msg.getMethod())){
		builder.get();
	} else if("POST".equalsIgnoreCase(msg.getMethod())){ 
		builder.post(RequestBody.create(null, Http.body(msg)));
	} else if("PUT".equalsIgnoreCase(msg.getMethod())){ 
		builder.put(RequestBody.create(null, Http.body(msg)));
	} else if("DELETE".equalsIgnoreCase(msg.getMethod())){ 
		builder.delete(); 
	} 
	return builder.build();
}
 
Example #2
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Make a POST call with a JSON body
 *
 * @param url      The full url to POST
 * @param params   The JSON params to add to the request
 * @param callback An OkHttp Callback
 */
public Call postWithJsonBody(String url, Map<String, Object> params, Callback callback) {
    JSONObject jsonObject = new JSONObject();
    for (String key : params.keySet()) {
        try {
            jsonObject.put(key, params.get(key));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, jsonObject.toString());
    Request request = new Builder().url(url).post(body).build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example #3
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Make a POST call without params
 *
 * @param url The full url to POST
 */
public <T extends AirMapBaseModel> Observable<T> post(final String url, final Class<T> classToInstantiate) {
    return Observable.defer(new Func0<Observable<T>>() {
        @Override
        public Observable<T> call() {
            try {
                Request request = new Builder().url(url).post(bodyFromMap(null)).tag(url).build();
                Response response = client.newCall(request).execute();
                T model = parseResponse(response, classToInstantiate);

                return Observable.just(model);
            } catch (IOException | IllegalAccessException | InstantiationException | JSONException | AirMapException e) {
                return Observable.error(e);
            }
        }
    });
}
 
Example #4
Source File: IlpOverHttpLink.java    From quilt with Apache License 2.0 6 votes vote down vote up
/**
 * Construct headers for an ILP-over-HTTP request.
 *
 * @return A newly constructed instance of {@link Headers}.
 */
private Headers constructHttpRequestHeaders() {
  final Headers.Builder headers = new Headers.Builder()
      // Defaults to ILP_OCTET_STREAM, but is replaced by whatever testConnection returns if it's a valid media-type.
      .add(HttpHeaders.ACCEPT, OCTET_STREAM.toString())
      .add(CONTENT_TYPE, OCTET_STREAM.toString())
      // Disable HTTP Caching of packets...
      .add(CACHE_CONTROL, "private, max-age=0, no-cache")
      .add(PRAGMA, "no-cache");

  // Set the Operator Address header, if present.
  headers.set(ILP_OPERATOR_ADDRESS_VALUE, getOperatorAddressSupplier().get().getValue());

  headers.add(HttpHeaders.AUTHORIZATION, BEARER_WITH_SPACE + this.authTokenSupplier.get());

  return headers.build();
}
 
Example #5
Source File: IlpOverHttpLink.java    From quilt with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to construct a {@link Request} containing the supplied {@code preparePacket}.
 *
 * @param preparePacket A {@link InterledgerPreparePacket} to send to the remote HTTP endpoint.
 *
 * @return A {@link Request} that can be used with an OkHttp client.
 */
private Request constructSendPacketRequest(final InterledgerPreparePacket preparePacket) {
  Objects.requireNonNull(preparePacket);

  try {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ilpCodecContext.write(preparePacket, byteArrayOutputStream);

    return new Builder()
        .headers(constructHttpRequestHeaders())
        .url(outgoingUrl)
        .post(
            RequestBody.create(byteArrayOutputStream.toByteArray(), APPLICATION_OCTET_STREAM)
        )
        .build();

  } catch (Exception e) {
    throw new LinkException(e.getMessage(), e, getLinkId());
  }
}
 
Example #6
Source File: LocOkHttpClient.java    From loc-framework with MIT License 6 votes vote down vote up
public <T> BaseResult<T> post(OkHttpClientBuilder okHttpClientBuilder) {
  checkBasicParam(okHttpClientBuilder);
  Builder builder = createRequestBuilder(okHttpClientBuilder.getUrl(),
      okHttpClientBuilder.getHeaders());

  FormBody.Builder formBuilder = new FormBody.Builder();
  Optional.ofNullable(okHttpClientBuilder.getParams()).ifPresent(c -> c.forEach(
      (key, value) -> {
        if (value != null) {
          formBuilder.add(key, value);
        } else {
          log.warn("key:{} is null", key);
        }
      }
  ));

  return returnBaseResult(builder.post(formBuilder.build()).build(),
      okHttpClientBuilder.getTypeReference()
  );
}
 
Example #7
Source File: LocOkHttpClient.java    From loc-framework with MIT License 6 votes vote down vote up
public <T> BaseResult<T> postEncoded(OkHttpClientBuilder hnPostBuilder, List<String> excludeEncode) {
  checkBasicParam(hnPostBuilder);
  Builder builder = createRequestBuilder(hnPostBuilder.getUrl(), hnPostBuilder.getHeaders());

  FormBody.Builder formBuilder = new FormBody.Builder();
  Optional.ofNullable(hnPostBuilder.getParams()).ifPresent(c -> c.forEach(
      (key, value) -> {
        if (value != null) {
          if (!excludeEncode.contains(key)) {
            formBuilder.add(key, value);
          } else {
            formBuilder.addEncoded(key, value);
          }
        } else {
          log.warn("key:{} is null", key);
        }
      }
  ));

  return returnBaseResult(builder.post(formBuilder.build()).build(),
      hnPostBuilder.getTypeReference()
  );
}
 
Example #8
Source File: HttpClientBuilder.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
public Request buildJsonGetRequest(String url, Map<String, String> headers) {
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder()
            .url(url)
            .addHeader("Authorization", "Basic " + base64Credentials)
            .addHeader("Accept", "application/json");

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }
    }

    return requestBuilder.get().build();
}
 
Example #9
Source File: HttpClientBuilder.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
public Request buildJsonDeleteRequest(String url, Map<String, String> headers) {
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder()
            .url(url)
            .addHeader("Authorization", "Basic " + base64Credentials)
            .addHeader("Accept", "application/json");

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }
    }

    return requestBuilder.delete().build();
}
 
Example #10
Source File: HttpClientBuilder.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
public Request buildJsonPostRequest(String url, Map<String, String> headers, String jsonPayload) {
    // make sure we are authenticated. see http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder()
            .url(url)
            .addHeader("Authorization", "Basic " + base64Credentials)
            .addHeader("Accept", "application/json");

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);

    return requestBuilder.post(body).build();
}
 
Example #11
Source File: HttpClientBuilder.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
public Request buildJsonPutRequest(String url, Map<String, String> headers, String jsonPayload) {
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder()
            .url(url)
            .addHeader("Authorization", "Basic " + base64Credentials)
            .addHeader("Accept", "application/json");

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);

    return requestBuilder.put(body).build();
}
 
Example #12
Source File: OkHttpTrelloHttpClient.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T postFileForObject(String url, File file, Class<T> responseType, String... params) {
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", file.getName(), RequestBody.create(APPLICATION_OCTET_STREAM, file))
            .build();

    try (Response response = httpClient.newCall(new Builder()
            .url(expandUrl(url, params))
            .post(requestBody)
            .build())
            .execute()) {
        return readResponse(responseType, response);
    } catch (IOException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #13
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Make a POST call with params
 *
 * @param url    The full url to POST
 * @param params The params to add to the request
 */
public Observable post(String url, Map<String, String> params) {
    try {
        Request request = new Builder().url(url).post(bodyFromMap(params)).tag(url).build();
        Response response = client.newCall(request).execute();
        return Observable.just(response);
    } catch (IOException e) {
        return Observable.error(e);
    }
}
 
Example #14
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Make a GET call
 *
 * @param url      The full url to GET
 * @param callback An OkHttp Callback
 */
public Call get(String url, Callback callback) {
    Request request = new Builder().url(url).get().tag(url).build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example #15
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
public String postSynchronous(String url, Map<String, String> params) throws IOException {
    Request request = new Builder().url(url).post(bodyFromMap(params)).tag(url).build();
    Response response = client.newCall(request).execute();
    String responseString = response.body().string();
    response.body().close();
    return responseString;
}
 
Example #16
Source File: FDSClient.java    From FimiX8-RE with MIT License 5 votes vote down vote up
public void upload2Fds(IFdsFileModel model, IFdsUploadListener listener) throws IOException {
    String url = model.getFileFdsUrl();
    this.call = new OkHttpClient().newCall(new Builder().header(OAuthConstants.HEADER_AUTHORIZATION, "Client-ID " + UUID.randomUUID()).url(url).put(new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", model.getFile().getName(), RequestBody.create(MediaType.parse("multipart/form-data"), new File(model.getZipFile().getAbsolutePath()))).build()).build());
    model.setState(FdsUploadState.LOADING);
    listener.onProgress(model, 0, model.getFile().length());
    Response response = this.call.execute();
    if (response.isSuccessful()) {
        Log.i("istep", "ResponseBody " + response.toString() + " " + model.getFile().getName());
        return;
    }
    Log.i("istep", "Unexpected code " + response);
    model.setState(FdsUploadState.FAILED);
}
 
Example #17
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Make a blocking GET call
 *
 * @param url The full url to GET
 * @return the string contents of the response body
 */
public String get(String url) throws IOException {
    Request request = new Builder().url(url).get().tag(url).build();
    Call call = client.newCall(request);
    Response response = call.execute();
    String responseString = response.body().string();
    response.body().close();
    return responseString;
}
 
Example #18
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Make a POST call with a JSON body
 *
 * @param url      The full url to POST
 * @param params   The JSON params to add to the request
 * @param callback An OkHttp Callback
 */
public Call postWithJsonBody(String url, JSONObject params, Callback callback) {
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, params.toString());
    Request request = new Builder().url(url).post(body).build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example #19
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Make a PATCH call with a JSON body
 *
 * @param url      The full url to POST
 * @param params   The JSON params to add to the request
 * @param callback An OkHttp Callback
 */
public Call patchWithJsonBody(String url, JSONObject params, Callback callback) {
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, params.toString());
    Request request = new Builder().url(url).patch(body).build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example #20
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Make a PATCH call with JSON body
 *
 * @param url      The full url to PATCH
 * @param params   The params to add to the request
 * @param callback An OkHttp Callback
 */
public Call patch(String url, JSONObject params, Callback callback) {
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, params.toString());
    Request request = new Builder().url(url).patch(body).build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example #21
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Make a DELETE call
 *
 * @param url      The full url to DELETE
 * @param callback An OkHttp Callback
 */
public Call delete(String url, Callback callback) {
    Request request = new Builder().url(url).delete().build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example #22
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Builds and Returns a CertificatePinner for AirMap API calls
 *
 * @return CertificatePinner
 */
private CertificatePinner getCertificatePinner() {
    String host = "api.airmap.com";
    String hostJP = "api.airmap.jp";
    return new CertificatePinner.Builder()
            .add(host, "sha256/47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=")
            .add(host, "sha256/CJlvFGiErgX6zPm0H+oO/TRbKOERdQOAYOs2nUlvIQ0=")
            .add(host, "sha256/8Rw90Ej3Ttt8RRkrg+WYDS9n7IS03bk5bjP/UXPtaY8=")
            .add(host, "sha256/Ko8tivDrEjiY90yGasP6ZpBU4jwXvHqVvQI0GS3GNdA=")
            .add(hostJP, "sha256/W5rhIQ2ZbJKFkRvsGDwQVS/H/NSixP33+Z/fpJ0O25Q=")
            .build();
}
 
Example #23
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates url based on map of params
 *
 * @param base The base url
 * @param map  The parameters to add to the url
 * @return The url with parameters embedded
 */
private HttpUrl urlBodyFromMap(String base, Map<String, String> map) {
    HttpUrl.Builder builder = HttpUrl.parse(base).newBuilder(base);
    for (Entry<String, String> entry : map.entrySet()) {
        if (entry.getValue() != null) {
            builder.addEncodedQueryParameter(entry.getKey(), entry.getValue());
        }
    }
    return builder.build();
}
 
Example #24
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Request Body from a map of params
 *
 * @param map The parameters to add to the body
 * @return The request body
 */
private FormBody bodyFromMap(Map<String, String> map) {
    FormBody.Builder formBody = new FormBody.Builder();
    if (map != null) {
        for (final Map.Entry<String, String> entrySet : map.entrySet()) {
            if (entrySet.getValue() != null) {
                formBody.add(entrySet.getKey(), entrySet.getValue());
            }
        }
    }
    return formBody.build();
}
 
Example #25
Source File: OkHttpRequest.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
public OkHttpRequest(OkHttpClient client, String url, HttpMethod method, String requestBody) {
	this.client = client;
	builder = new Request.Builder().url(url);
	
	RequestBody requestBodyObj = requestBody != null ? RequestBody.create(null, requestBody) : null;
	builder.method(method.toString(), requestBodyObj);
}
 
Example #26
Source File: HttpClientBuilder.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
public Request buildGetRequest(String url, Map<String, String> headers) {
    String base64Credentials = buildBase64Credentials();

    Builder requestBuilder = new Request.Builder()
            .url(url)
            .addHeader("Authorization", "Basic " + base64Credentials);

    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.addHeader(header.getKey(), header.getValue());
        }
    }

    return requestBuilder.get().build();
}
 
Example #27
Source File: HttpProtocol.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
private void addCookiesToRequest(Builder rb, String url, Metadata md) {
    String[] cookieStrings = md.getValues(RESPONSE_COOKIES_HEADER, protocolMDprefix);
    if (cookieStrings == null || cookieStrings.length == 0) {
        return;
    }
    try {
        List<Cookie> cookies = CookieConverter.getCookies(cookieStrings,
                new URL(url));
        for (Cookie c : cookies) {
            rb.addHeader("Cookie", c.getName() + "=" + c.getValue());
        }
    } catch (MalformedURLException e) { // Bad url , nothing to do
    }
}
 
Example #28
Source File: HybridThriftOverHttpServiceImpl.java    From buck with Apache License 2.0 5 votes vote down vote up
/** @inheritDoc */
@Override
public ThriftResponse makeRequestSync(
    HybridThriftRequestHandler<ThriftRequest> request,
    HybridThriftResponseHandler<ThriftResponse> responseHandler)
    throws IOException {
  byte[] serializedThriftData =
      ThriftUtil.serialize(args.getThriftProtocol(), request.getRequest());
  long totalRequestSizeBytes =
      4 + serializedThriftData.length + request.getTotalPayloadsSizeBytes();
  Builder builder =
      new Builder().addHeader(PROTOCOL_HEADER, args.getThriftProtocol().toString().toLowerCase());
  builder.post(
      new RequestBody() {
        @Override
        public MediaType contentType() {
          return HYBRID_THRIFT_STREAM_CONTENT_TYPE;
        }

        @Override
        public long contentLength() {
          return totalRequestSizeBytes;
        }

        @Override
        public void writeTo(BufferedSink bufferedSink) throws IOException {
          try (DataOutputStream outputStream =
              new DataOutputStream(bufferedSink.outputStream())) {
            writeToStream(outputStream, serializedThriftData, request);
          }
        }
      });

  HttpResponse response = args.getService().makeRequest(args.getHybridThriftPath(), builder);
  try (DataInputStream bodyStream = new DataInputStream(response.getBody())) {
    return readFromStream(bodyStream, args.getThriftProtocol(), responseHandler);
  }
}
 
Example #29
Source File: RestClientCall.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
private RequestBody prepareBody(Object body) throws JsonProcessingException {
  RequestBody requestBody = null;
  String json = "";

  if (body == null) {
    logger.debug("The request has no body");
  } else if (body instanceof String) {
    json = (String) body;
    logger.debug("Passed String rest object: [{}]", json);
    requestBody = RequestBody.create(this.mediaType, json);
  } else if (body instanceof Map) {
    Map<String, String> paramMap = ((Map) body);
    logger.debug("Passed parameter map, keys: [{}]", paramMap.keySet());
    FormBody.Builder form = new FormBody.Builder();
    for (Map.Entry<String, String> param : paramMap.entrySet()) {
      form.add(param.getKey(), param.getValue());
    }
    logger.debug("Created form {}", json);
    requestBody = form.build();
  } else {
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    json = ow.writeValueAsString(body);
    logger.debug("Converted rest object: {}", json);
    requestBody = RequestBody.create(this.mediaType, json);
  }

  return requestBody;
}
 
Example #30
Source File: DiscoveredServiceWorkItemHandler.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected OkHttpClient buildHttpClient() {
    if (http == null) {
        LOGGER.debug("Creating and caching a new reference of OkHttpClient");
        http = new OkHttpClient.Builder()
                                         .connectTimeout(60, TimeUnit.SECONDS)
                                         .writeTimeout(60, TimeUnit.SECONDS)
                                         .readTimeout(60, TimeUnit.SECONDS)
                                         .build();
    }
    return http;
}