Java Code Examples for okhttp3.Request.Builder#post()

The following examples show how to use okhttp3.Request.Builder#post() . 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: Server.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
public static String exchange(String url, String method, String json,
        int timeoutSec) throws IOException {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(timeoutSec, SECONDS);
    builder.readTimeout(timeoutSec, SECONDS);
    builder.writeTimeout(timeoutSec, SECONDS);
    OkHttpClient client = builder.build();

    Builder requestBuilder = new Request.Builder().url(url);
    switch (method) {
    case GET:
        requestBuilder.get();
        break;
    case DELETE:
        requestBuilder.delete();
        break;
    default:
    case POST:
        RequestBody body = RequestBody.create(JSON, json);
        requestBuilder.post(body);
        break;
    }
    Response response = client.newCall(requestBuilder.build()).execute();
    return response.body().string();
}
 
Example 3
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 4
Source File: HttpProtocol.java    From storm-crawler with Apache License 2.0 4 votes vote down vote up
@Override
public ProtocolResponse getProtocolOutput(String url, final Metadata metadata) throws Exception {
    Builder rb = new Request.Builder().url(url);
    customRequestHeaders.forEach((k) -> {
        rb.header(k[0], k[1]);
    });

    if (metadata != null) {
        String lastModified = metadata.getFirstValue("last-modified");
        if (StringUtils.isNotBlank(lastModified)) {
            rb.header("If-Modified-Since",
                    HttpHeaders.formatHttpDate(lastModified));
        }

        String ifNoneMatch = metadata.getFirstValue("etag", protocolMDprefix);
        if (StringUtils.isNotBlank(ifNoneMatch)) {
            rb.header("If-None-Match", ifNoneMatch);
        }

        String accept = metadata.getFirstValue("http.accept");
        if (StringUtils.isNotBlank(accept)) {
            rb.header("Accept", accept);
        }

        String acceptLanguage = metadata.getFirstValue("http.accept.language");
        if (StringUtils.isNotBlank(acceptLanguage)) {
            rb.header("Accept-Language", acceptLanguage);
        }

        if (useCookies) {
            addCookiesToRequest(rb, url, metadata);
        }
        
        String postJSONData = metadata.getFirstValue("http.post.json");
        if (StringUtils.isNotBlank(postJSONData)) {
            RequestBody body = RequestBody.create(JSON, postJSONData);
            rb.post(body);
        }
    }

    Request request = rb.build();
    Call call = client.newCall(request);

    try (Response response = call.execute()) {

        byte[] bytes = new byte[] {};

        Metadata responsemetadata = new Metadata();
        Headers headers = response.headers();

        for (int i = 0, size = headers.size(); i < size; i++) {
            String key = headers.name(i);
            String value = headers.value(i);

            if (key.equals(ProtocolResponse.REQUEST_HEADERS_KEY)
                    || key.equals(ProtocolResponse.RESPONSE_HEADERS_KEY)) {
                value = new String(Base64.getDecoder().decode(value));
            }

            responsemetadata.addValue(key.toLowerCase(Locale.ROOT), value);
        }

        MutableObject trimmed = new MutableObject(TrimmedContentReason.NOT_TRIMMED);
        bytes = toByteArray(response.body(), trimmed);
        if (trimmed.getValue() != TrimmedContentReason.NOT_TRIMMED) {
            if (!call.isCanceled()) {
                call.cancel();
            }
            responsemetadata.setValue(ProtocolResponse.TRIMMED_RESPONSE_KEY,
                    "true");
            responsemetadata.setValue(
                    ProtocolResponse.TRIMMED_RESPONSE_REASON_KEY,
                    trimmed.getValue().toString().toLowerCase(Locale.ROOT));
            LOG.warn("HTTP content trimmed to {}", bytes.length);
        }

        return new ProtocolResponse(bytes, response.code(), responsemetadata);
    }
}