Search in sources :

Example 1 with RequestBuilder

use of com.ning.http.client.RequestBuilder in project jersey by jersey.

the class CustomizersTest method testCustomizers.

/**
     * Jersey-2540 related test.
     */
@Test
public void testCustomizers() {
    Response response;
    // now using global request customizer
    response = target("test").request().post(text("echo"));
    assertEquals("POSTed echo", response.readEntity(String.class));
    assertEquals("tested", response.getHeaderString("X-Test-Config"));
    assertEquals("tested-global", response.getHeaderString("X-Test-Request"));
    // now using request-specific request customizer
    final Invocation.Builder builder = target("test").request();
    GrizzlyConnectorProvider.register(builder, new GrizzlyConnectorProvider.RequestCustomizer() {

        @Override
        public RequestBuilder customize(ClientRequest requestContext, RequestBuilder requestBuilder) {
            requestBuilder.addHeader("X-Test-Request", "tested-per-request");
            return requestBuilder;
        }
    });
    response = builder.post(text("echo"));
    assertEquals("POSTed echo", response.readEntity(String.class));
    assertEquals("tested", response.getHeaderString("X-Test-Config"));
    assertEquals("tested-per-request", response.getHeaderString("X-Test-Request"));
    // now using global request customizer again
    response = target("test").request().post(text("echo"));
    assertEquals("POSTed echo", response.readEntity(String.class));
    assertEquals("tested", response.getHeaderString("X-Test-Config"));
    assertEquals("tested-global", response.getHeaderString("X-Test-Request"));
}
Also used : Response(javax.ws.rs.core.Response) Invocation(javax.ws.rs.client.Invocation) RequestBuilder(com.ning.http.client.RequestBuilder) ClientRequest(org.glassfish.jersey.client.ClientRequest) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 2 with RequestBuilder

use of com.ning.http.client.RequestBuilder in project jersey by jersey.

the class GrizzlyConnector method translate.

private com.ning.http.client.Request translate(final ClientRequest requestContext) {
    final String strMethod = requestContext.getMethod();
    final URI uri = requestContext.getUri();
    RequestBuilder builder = new RequestBuilder(strMethod).setUrl(uri.toString());
    builder.setFollowRedirects(requestContext.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true));
    if (requestContext.hasEntity()) {
        final RequestEntityProcessing entityProcessing = requestContext.resolveProperty(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class);
        if (entityProcessing == RequestEntityProcessing.BUFFERED) {
            byte[] entityBytes = bufferEntity(requestContext);
            builder = builder.setBody(entityBytes);
        } else {
            final FeedableBodyGenerator bodyGenerator = new FeedableBodyGenerator();
            final Integer chunkSize = requestContext.resolveProperty(ClientProperties.CHUNKED_ENCODING_SIZE, ClientProperties.DEFAULT_CHUNK_SIZE);
            bodyGenerator.setMaxPendingBytes(chunkSize);
            final FeedableBodyGenerator.Feeder feeder = new FeedableBodyGenerator.SimpleFeeder(bodyGenerator) {

                @Override
                public void flush() throws IOException {
                    requestContext.writeEntity();
                }
            };
            requestContext.setStreamProvider(new OutboundMessageContext.StreamProvider() {

                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return new FeederAdapter(feeder);
                }
            });
            bodyGenerator.setFeeder(feeder);
            builder.setBody(bodyGenerator);
        }
    }
    final GrizzlyConnectorProvider.RequestCustomizer requestCustomizer = requestContext.resolveProperty(GrizzlyConnectorProvider.REQUEST_CUSTOMIZER, GrizzlyConnectorProvider.RequestCustomizer.class);
    if (requestCustomizer != null) {
        builder = requestCustomizer.customize(requestContext, builder);
    }
    return builder.build();
}
Also used : RequestBuilder(com.ning.http.client.RequestBuilder) RequestEntityProcessing(org.glassfish.jersey.client.RequestEntityProcessing) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) URI(java.net.URI) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) FeedableBodyGenerator(com.ning.http.client.providers.grizzly.FeedableBodyGenerator)

Example 3 with RequestBuilder

use of com.ning.http.client.RequestBuilder in project Singularity by HubSpot.

the class SingularityHealthchecker method asyncHealthcheck.

private void asyncHealthcheck(final SingularityTask task) {
    final SingularityHealthcheckAsyncHandler handler = new SingularityHealthcheckAsyncHandler(exceptionNotifier, configuration, this, newTaskChecker, taskManager, task);
    final Optional<String> uri = getHealthcheckUri(task);
    if (!uri.isPresent()) {
        saveFailure(handler, "Invalid healthcheck uri or ports not present");
        return;
    }
    final Integer timeoutSeconds = task.getTaskRequest().getDeploy().getHealthcheck().isPresent() ? task.getTaskRequest().getDeploy().getHealthcheck().get().getResponseTimeoutSeconds().or(configuration.getHealthcheckTimeoutSeconds()) : configuration.getHealthcheckTimeoutSeconds();
    try {
        PerRequestConfig prc = new PerRequestConfig();
        prc.setRequestTimeoutInMs((int) TimeUnit.SECONDS.toMillis(timeoutSeconds));
        RequestBuilder builder = new RequestBuilder("GET");
        builder.setFollowRedirects(true);
        builder.setUrl(uri.get());
        builder.setPerRequestConfig(prc);
        LOG.trace("Issuing a healthcheck ({}) for task {} with timeout {}s", uri.get(), task.getTaskId(), timeoutSeconds);
        http.prepareRequest(builder.build()).execute(handler);
    } catch (Throwable t) {
        LOG.debug("Exception while preparing healthcheck ({}) for task ({})", uri, task.getTaskId(), t);
        exceptionNotifier.notify(String.format("Error preparing healthcheck (%s)", t.getMessage()), t, ImmutableMap.of("taskId", task.getTaskId().toString()));
        saveFailure(handler, String.format("Healthcheck failed due to exception: %s", t.getMessage()));
    }
}
Also used : RequestBuilder(com.ning.http.client.RequestBuilder) PerRequestConfig(com.ning.http.client.PerRequestConfig)

Example 4 with RequestBuilder

use of com.ning.http.client.RequestBuilder in project protools by SeanDragon.

the class ToolHttp method sendHttp.

/**
 * 用于请求http
 *
 * @param send
 *         里面包含请求的信息
 *
 * @return 响应的信息
 */
public static HttpReceive sendHttp(HttpSend send, HttpBuilder httpBuilder) {
    HttpReceive httpReceive = new HttpReceive();
    httpReceive.setHaveError(true);
    String url = send.getUrl();
    URI uri;
    try {
        uri = new URL(url).toURI();
    } catch (MalformedURLException | URISyntaxException e) {
        httpReceive.setErrMsg("不是一个有效的URL").setThrowable(e);
        return httpReceive;
    }
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if (HttpScheme.HTTP.equalsIgnoreCase(scheme)) {
            port = 80;
        } else if (HttpScheme.HTTPS.equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }
    Map<String, Object> param = send.getParams();
    Map<String, Object> sendHeaders = send.getHeaders();
    HttpMethod method = send.getMethod();
    Charset charset = send.getCharset();
    AsyncHttpClient asyncHttpClient = httpBuilder.buildDefaultClient();
    RequestBuilder builder = new RequestBuilder(method.name());
    AsyncHttpClient.BoundRequestBuilder requestBuilder = asyncHttpClient.prepareRequest(builder.build());
    // 设置编码
    requestBuilder.setBodyEncoding(charset.toString());
    if (param != null) {
        param.forEach((key, value) -> requestBuilder.addQueryParam(key, value.toString()));
    }
    // 设置基本请求头
    requestBuilder.addHeader(HttpHeaderNames.CONTENT_TYPE.toString(), HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED + ";charset" + charset.toString()).addHeader(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString()).addHeader(HttpHeaderNames.ACCEPT_ENCODING.toString(), HttpHeaderValues.GZIP_DEFLATE.toString()).addHeader(HttpHeaderNames.USER_AGENT.toString(), "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)").addHeader(HttpHeaderNames.CACHE_CONTROL.toString(), "max-age=0").addHeader(HttpHeaderNames.HOST.toString(), host + ":" + port).addHeader("DNT", "1");
    if (sendHeaders != null) {
        sendHeaders.forEach((key, value) -> requestBuilder.addHeader(key, value.toString()));
    }
    // TODO: 2017/7/27 Cookie未加入
    ListenableFuture<Response> future = requestBuilder.execute();
    try {
        Response response = future.get();
        Map<String, String> responseHeaderMap = Maps.newHashMap();
        if (send.getNeedReceiveHeaders()) {
            FluentCaseInsensitiveStringsMap responseHeaders = response.getHeaders();
            responseHeaders.forEach((k, v) -> {
                if (v.size() == 1) {
                    responseHeaderMap.put(k, v.get(0));
                } else {
                    responseHeaderMap.put(k, ToolJson.anyToJson(v));
                }
            });
        }
        int responseStatusCode = response.getStatusCode();
        if (responseStatusCode != 200) {
            throw new HttpException("本次请求响应码不是200,是" + responseStatusCode);
        }
        String responseBody = response.getResponseBody();
        if (log.isDebugEnabled()) {
            log.debug(responseBody);
        }
        httpReceive.setStatusCode(responseStatusCode).setStatusText(response.getStatusText()).setResponseBody(responseBody).setResponseHeader(responseHeaderMap).setHaveError(false);
    } catch (InterruptedException e) {
        httpReceive.setErrMsg("http组件出现问题!").setThrowable(e);
    } catch (IOException e) {
        httpReceive.setErrMsg("获取返回内容失败!").setThrowable(e);
    } catch (ExecutionException e) {
        httpReceive.setErrMsg("访问URL失败!").setThrowable(e);
    } catch (HttpException e) {
        httpReceive.setErrMsg(e.getMessage()).setThrowable(e);
    }
    if (httpReceive.getHaveError()) {
        if (log.isWarnEnabled()) {
            Throwable throwable = httpReceive.getThrowable();
            log.warn(ToolFormat.toException(throwable), throwable);
        }
    }
    httpReceive.setIsDone(true);
    return httpReceive;
}
Also used : HttpReceive(pro.tools.http.pojo.HttpReceive) MalformedURLException(java.net.MalformedURLException) RequestBuilder(com.ning.http.client.RequestBuilder) Charset(java.nio.charset.Charset) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) Response(com.ning.http.client.Response) FluentCaseInsensitiveStringsMap(com.ning.http.client.FluentCaseInsensitiveStringsMap) HttpException(pro.tools.http.pojo.HttpException) ExecutionException(java.util.concurrent.ExecutionException) HttpMethod(pro.tools.http.pojo.HttpMethod) AsyncHttpClient(com.ning.http.client.AsyncHttpClient)

Example 5 with RequestBuilder

use of com.ning.http.client.RequestBuilder in project traccar by traccar.

the class StatisticsManager method checkSplit.

private void checkSplit() {
    int currentUpdate = Calendar.getInstance().get(SPLIT_MODE);
    if (lastUpdate.getAndSet(currentUpdate) != currentUpdate) {
        Statistics statistics = new Statistics();
        statistics.setCaptureTime(new Date());
        statistics.setActiveUsers(users.size());
        statistics.setActiveDevices(devices.size());
        statistics.setRequests(requests);
        statistics.setMessagesReceived(messagesReceived);
        statistics.setMessagesStored(messagesStored);
        statistics.setMailSent(mailSent);
        statistics.setSmsSent(smsSent);
        statistics.setGeocoderRequests(geocoderRequests);
        statistics.setGeolocationRequests(geolocationRequests);
        try {
            Context.getDataManager().addObject(statistics);
        } catch (SQLException e) {
            Log.warning(e);
        }
        String url = Context.getConfig().getString("server.statistics");
        if (url != null) {
            String time = ISODateTimeFormat.dateTime().print(statistics.getCaptureTime().getTime());
            Request request = new RequestBuilder("POST").setUrl(url).addHeader("Content-Type", "application/x-www-form-urlencoded").addFormParam("version", Log.getAppVersion()).addFormParam("captureTime", time).addFormParam("activeUsers", String.valueOf(statistics.getActiveUsers())).addFormParam("activeDevices", String.valueOf(statistics.getActiveDevices())).addFormParam("requests", String.valueOf(statistics.getRequests())).addFormParam("messagesReceived", String.valueOf(statistics.getMessagesReceived())).addFormParam("messagesStored", String.valueOf(statistics.getMessagesStored())).addFormParam("mailSent", String.valueOf(statistics.getMailSent())).addFormParam("smsSent", String.valueOf(statistics.getSmsSent())).addFormParam("geocoderRequests", String.valueOf(statistics.getGeocoderRequests())).addFormParam("geolocationRequests", String.valueOf(statistics.getGeolocationRequests())).build();
            Context.getAsyncHttpClient().prepareRequest(request).execute();
        }
        users.clear();
        devices.clear();
        requests = 0;
        messagesReceived = 0;
        messagesStored = 0;
        mailSent = 0;
        smsSent = 0;
        geocoderRequests = 0;
        geolocationRequests = 0;
    }
}
Also used : RequestBuilder(com.ning.http.client.RequestBuilder) SQLException(java.sql.SQLException) Request(com.ning.http.client.Request) Statistics(org.traccar.model.Statistics) Date(java.util.Date)

Aggregations

RequestBuilder (com.ning.http.client.RequestBuilder)10 IOException (java.io.IOException)7 Request (com.ning.http.client.Request)6 Response (com.ning.http.client.Response)5 AsyncHttpClient (com.ning.http.client.AsyncHttpClient)4 Test (org.junit.Test)4 AsyncHttpClientConfig (com.ning.http.client.AsyncHttpClientConfig)3 NettyAsyncHttpProvider (com.ning.http.client.providers.netty.NettyAsyncHttpProvider)3 HttpRequest (io.netty.handler.codec.http.HttpRequest)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 URISyntaxException (java.net.URISyntaxException)3 HttpResponseBodyPart (com.ning.http.client.HttpResponseBodyPart)2 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)2 URI (java.net.URI)2 HttpResponse (org.apache.http.HttpResponse)2 RandomEndpointStrategy (co.cask.cdap.common.discovery.RandomEndpointStrategy)1 FluentCaseInsensitiveStringsMap (com.ning.http.client.FluentCaseInsensitiveStringsMap)1 PerRequestConfig (com.ning.http.client.PerRequestConfig)1 FeedableBodyGenerator (com.ning.http.client.providers.grizzly.FeedableBodyGenerator)1 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)1