當前位置: 首頁>>代碼示例>>Java>>正文


Java RequestBuilder.create方法代碼示例

本文整理匯總了Java中org.apache.http.client.methods.RequestBuilder.create方法的典型用法代碼示例。如果您正苦於以下問題:Java RequestBuilder.create方法的具體用法?Java RequestBuilder.create怎麽用?Java RequestBuilder.create使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.http.client.methods.RequestBuilder的用法示例。


在下文中一共展示了RequestBuilder.create方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: send

import org.apache.http.client.methods.RequestBuilder; //導入方法依賴的package包/類
public RawHttpResponse<CloseableHttpResponse> send(RawHttpRequest request) throws IOException {
    RequestBuilder builder = RequestBuilder.create(request.getMethod());
    builder.setUri(request.getUri());
    builder.setVersion(toProtocolVersion(request.getStartLine().getHttpVersion()));
    request.getHeaders().getHeaderNames().forEach((name) ->
            request.getHeaders().get(name).forEach(value ->
                    builder.addHeader(new BasicHeader(name, value))));

    request.getBody().ifPresent(b -> builder.setEntity(new InputStreamEntity(b.asStream())));

    CloseableHttpResponse response = httpClient.execute(builder.build());

    RawHttpHeaders headers = readHeaders(response);

    @Nullable LazyBodyReader body;
    if (response.getEntity() != null) {
        OptionalLong headerLength = RawHttp.parseContentLength(headers);
        @Nullable Long length = headerLength.isPresent() ? headerLength.getAsLong() : null;
        BodyType bodyType = RawHttp.getBodyType(headers, length);
        body = new LazyBodyReader(bodyType, response.getEntity().getContent(), length, false);
    } else {
        body = null;
    }

    return new RawHttpResponse<>(response, request, adaptStatus(response.getStatusLine()), headers, body);
}
 
開發者ID:renatoathaydes,項目名稱:rawhttp,代碼行數:27,代碼來源:RawHttpComponentsClient.java

示例2: httpRequest

import org.apache.http.client.methods.RequestBuilder; //導入方法依賴的package包/類
HttpUriRequest httpRequest(HTTPRequest request) {
    HTTPMethod method = request.method();
    String uri = request.uri();
    logger.debug("[request] method={}, uri={}", method, uri);
    RequestBuilder builder = RequestBuilder.create(method.name());
    try {
        builder.setUri(uri);
    } catch (IllegalArgumentException e) {
        throw new HTTPClientException("uri is invalid, uri=" + uri, "INVALID_URL", e);
    }

    request.headers().forEach((name, value) -> {
        logger.debug("[request:header] {}={}", name, value);
        builder.setHeader(name, value);
    });

    request.params().forEach((name, value) -> {
        logger.debug("[request:param] {}={}", name, value);
        builder.addParameter(name, value);
    });

    byte[] body = request.body();
    if (body != null) {
        ContentType contentType = request.contentType();
        logger.debug("[request] contentType={}, body={}", contentType, LogParam.of(request.body()));
        org.apache.http.entity.ContentType type = org.apache.http.entity.ContentType.create(contentType.mediaType(), contentType.charset().orElse(null));
        builder.setEntity(new ByteArrayEntity(request.body(), type));
    }

    return builder.build();
}
 
開發者ID:neowu,項目名稱:core-ng-project,代碼行數:32,代碼來源:HTTPClientImpl.java

示例3: privateRequest

import org.apache.http.client.methods.RequestBuilder; //導入方法依賴的package包/類
private ApiResponse privateRequest(String httpMethod, String endpoint, String body, HashMap<String, String> query, int requestcount) {
    if (!ApiSettings.isValid())
        throw new IllegalStateException("ApiSettings have an invalid state");
    String endpointFinal = ApiSettings.getApiEndpoint() + endpoint;

    try {
        StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);

        RequestBuilder requestBuilder = RequestBuilder.create(httpMethod);
        requestBuilder.addHeader("Voat-ApiKey", ApiSettings.getPublicKey());
        requestBuilder.setUri(endpointFinal);

        if (!httpMethod.equals("GET"))
            requestBuilder.setEntity(entity);

        if (query != null)
            for (String key : query.keySet()) {
                requestBuilder.addParameter(key, query.get(key));
            }

        HttpUriRequest build = requestBuilder.build();

        Authenticator.getInstance().authenticateRequest(build);
        String s = HttpHelper.sendRequest(build);

        HashMap<String, Object> json = JsonHelper.getInstance().fromJson(s);
        return new ApiResponse(json);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
開發者ID:M3gaFr3ak,項目名稱:Voat-API-Java-Wrapper,代碼行數:35,代碼來源:APIProxy.java

示例4: login

import org.apache.http.client.methods.RequestBuilder; //導入方法依賴的package包/類
public void login(String username, String password) throws IOException, ParseException {
    RequestBuilder builder = RequestBuilder.create("POST");
    StringEntity entity = new StringEntity(String.format("grant_type=password&username=%s&password=%s", username, password), ContentType.APPLICATION_FORM_URLENCODED);
    builder.setEntity(entity);
    builder.addHeader("Voat-ApiKey", ApiSettings.getPublicKey());

    builder.setUri(ApiSettings.getApiEndpoint() + "api/token");

    String response = HttpHelper.sendRequest(builder.build());
    HashMap<String, Object> map = JsonHelper.getInstance().fromJson(response);
    accessToken = (String) map.get("access_token");
}
 
開發者ID:M3gaFr3ak,項目名稱:Voat-API-Java-Wrapper,代碼行數:13,代碼來源:Authenticator.java

示例5: should_set_not_sampled_on_the_context_when_there_is_no_span

import org.apache.http.client.methods.RequestBuilder; //導入方法依賴的package包/類
@Test
public void should_set_not_sampled_on_the_context_when_there_is_no_span() throws Exception {
	RequestBuilder requestBuilder = RequestBuilder.create("GET");

	this.customizer.inject(null, this.customizer.toSpanTextMap(requestBuilder));

	HttpUriRequest request = requestBuilder.build();
	Header header = request.getFirstHeader(Span.SAMPLED_NAME);
	then(header.getName()).isEqualTo(Span.SAMPLED_NAME);
	then(header.getValue()).isEqualTo(Span.SPAN_NOT_SAMPLED);
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-sleuth,代碼行數:12,代碼來源:ApacheHttpClientRibbonRequestCustomizerTests.java

示例6: should_set_tracing_headers_on_the_context_when_there_is_a_span

import org.apache.http.client.methods.RequestBuilder; //導入方法依賴的package包/類
@Test
public void should_set_tracing_headers_on_the_context_when_there_is_a_span() throws Exception {
	RequestBuilder requestBuilder = RequestBuilder.create("GET");

	this.customizer.inject(this.span, this.customizer.toSpanTextMap(requestBuilder));

	HttpUriRequest request = requestBuilder.build();
	thenThereIsAHeaderWithNameAndValue(request, Span.SPAN_ID_NAME, "0000000000000001");
	thenThereIsAHeaderWithNameAndValue(request, Span.TRACE_ID_NAME, "0000000000000002");
	thenThereIsAHeaderWithNameAndValue(request, Span.PARENT_ID_NAME, "0000000000000003");
	thenThereIsAHeaderWithNameAndValue(request, Span.PROCESS_ID_NAME, "processId");
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-sleuth,代碼行數:13,代碼來源:ApacheHttpClientRibbonRequestCustomizerTests.java

示例7: should_not_set_duplicate_tracing_headers_on_the_context_when_there_is_a_span

import org.apache.http.client.methods.RequestBuilder; //導入方法依賴的package包/類
@Test
public void should_not_set_duplicate_tracing_headers_on_the_context_when_there_is_a_span() throws Exception {
	RequestBuilder requestBuilder = RequestBuilder.create("GET");

	this.customizer.inject(this.span, this.customizer.toSpanTextMap(requestBuilder));
	this.customizer.inject(this.span, this.customizer.toSpanTextMap(requestBuilder));

	HttpUriRequest request = requestBuilder.build();
	thenThereIsAHeaderWithNameAndValue(request, Span.SPAN_ID_NAME, "0000000000000001");
	thenThereIsAHeaderWithNameAndValue(request, Span.TRACE_ID_NAME, "0000000000000002");
	thenThereIsAHeaderWithNameAndValue(request, Span.PARENT_ID_NAME, "0000000000000003");
	thenThereIsAHeaderWithNameAndValue(request, Span.PROCESS_ID_NAME, "processId");
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-sleuth,代碼行數:14,代碼來源:ApacheHttpClientRibbonRequestCustomizerTests.java

示例8: toHttpUriRequest

import org.apache.http.client.methods.RequestBuilder; //導入方法依賴的package包/類
HttpUriRequest toHttpUriRequest(Request request, Request.Options options) throws
        UnsupportedEncodingException, MalformedURLException, URISyntaxException {
    RequestBuilder requestBuilder = RequestBuilder.create(request.method());

    //per request timeouts
    RequestConfig requestConfig = RequestConfig
            .custom()
            .setConnectTimeout(options.connectTimeoutMillis())
            .setSocketTimeout(options.readTimeoutMillis())
            .build();
    requestBuilder.setConfig(requestConfig);

    URI uri = new URIBuilder(request.url()).build();

    requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath());

    //request query params
    List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset().name
            ());
    for (NameValuePair queryParam : queryParams) {
        requestBuilder.addParameter(queryParam);
    }

    //request headers
    boolean hasAcceptHeader = false;
    for (Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
        String headerName = headerEntry.getKey();
        if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
            hasAcceptHeader = true;
        }

        if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
            // The 'Content-Length' header is always set by the Apache client and it
            // doesn't like us to set it as well.
            continue;
        }

        for (String headerValue : headerEntry.getValue()) {
            requestBuilder.addHeader(headerName, headerValue);
        }
    }
    //some servers choke on the default accept string, so we'll set it to anything
    if (!hasAcceptHeader) {
        requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*");
    }

    //request body
    if (request.body() != null) {
        HttpEntity entity = null;
        if (request.charset() != null) {
            ContentType contentType = getContentType(request);
            String content = new String(request.body(), request.charset());
            entity = new StringEntity(content, contentType);
        } else {
            entity = new ByteArrayEntity(request.body());
        }

        requestBuilder.setEntity(entity);
    }

    return requestBuilder.build();
}
 
開發者ID:wso2,項目名稱:msf4j,代碼行數:63,代碼來源:ApacheHttpClient.java


注:本文中的org.apache.http.client.methods.RequestBuilder.create方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。