本文整理汇总了Java中io.vertx.ext.web.client.HttpRequest.putHeader方法的典型用法代码示例。如果您正苦于以下问题:Java HttpRequest.putHeader方法的具体用法?Java HttpRequest.putHeader怎么用?Java HttpRequest.putHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类io.vertx.ext.web.client.HttpRequest
的用法示例。
在下文中一共展示了HttpRequest.putHeader方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: buildRequest
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
private HttpRequest<JsonObject> buildRequest(String requestURI, RequestParameters parameters) {
HttpRequest<JsonObject> request = client.post(requestURI)
.as(BodyCodec.jsonObject())
.putHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
.setQueryParam("properties", parameters.getProperties().toString())
.setQueryParam("pipelineLanguage", parameters.getLanguage().name());
if (options.getUsername() != null && options.getPassword() != null) {
request.putHeader("Authorization",
"Basic " + Base64.getEncoder().encodeToString(String.join(":", options.getUsername(), options.getPassword()).getBytes()));
}
if (parameters.getPattern() != null) {
request.setQueryParam("pattern", parameters.getPattern())
.setQueryParam("filter", String.valueOf(parameters.isFilter()));
}
return request;
}
示例2: testImplicitMode
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
public void testImplicitMode() {
vertx = Vertx.vertx();
WebClient client = WebClient.create(vertx);
HttpRequest<Buffer> request = client.postAbs("http://admin:[email protected]:8080/oauth/authorize?response_type=token&scope=read%20write&client_id=myClientId&redirect_uri=http://example.com");
request.putHeader("Authorization", getHeader());
request.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
//String location = response.getHeader("Location");
String body = response.bodyAsString();
System.out.println("Implicit Mode Get Token" + body + " status code" + response.statusCode() + " Location=");
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
示例3: sendRequest
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
@Override
protected void sendRequest(ServerRequest request, ServerRequestEventFactory requestEventFactory) {
Path pathAnnotation = request.getClass().getAnnotation(Path.class);
HttpMethod method = HttpMethod.valueOf(pathAnnotation.method());
String absoluteURI = buildPath(pathAnnotation, request.requestBean());
HttpRequest<Buffer> httpRequest = webClient.requestAbs(method, absoluteURI);
if (nonNull(csrfToken))
httpRequest.putHeader(DEFAULT_HEADER_NAME, csrfToken);
((Map<String, String>) request.headers()).forEach(httpRequest::putHeader);
httpRequest.putHeader("Content-Type", "application/json");
if (HttpMethod.POST.equals(method) || HttpMethod.PUT.equals(method) || HttpMethod.PATCH.equals(method))
httpRequest.putHeader("Accept", "application/json");
ParameterizedType parameterizedType = (ParameterizedType) request.getClass().getGenericSuperclass();
Type responseType = parameterizedType.getActualTypeArguments()[RRESPONSE_TYPE_INDEX];
try {
Class<? extends ResponseBean> clazz = (Class<? extends ResponseBean>) Class.forName(responseType.getTypeName());
httpRequest.sendJson(request.requestBean(), event -> {
if (event.succeeded()) {
this.csrfToken = event.result().headers().getAll("Set-Cookie")
.stream()
.filter(header -> header.startsWith("XSRF-TOKEN"))
.map(header -> header.substring(0, header.indexOf(";")).replace("XSRF-TOKEN=", ""))
.findFirst().orElse(csrfToken);
requestEventFactory.makeSuccess(request, Json.decodeValue(event.result().body(), clazz)).fire();
} else
requestEventFactory.makeFailed(request, event.cause()).fire();
});
} catch (ClassNotFoundException e) {
requestEventFactory.makeFailed(request, e);
}
}
示例4: testAuthorizationCode
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
public void testAuthorizationCode() {
vertx = Vertx.vertx();
WebClient client = WebClient.create(vertx);
HttpRequest<Buffer> request = client.postAbs("http://admin:[email protected]:8080/oauth/authorize?client_id=myClientId&client_secret=myClientSecret&redirect_uri=http://example.com&response_type=code&scope=read%20write");
request.putHeader("Authorization", getHeader());
request.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
String body = response.bodyAsString();
System.out.println("Authorization Code Mode Get Token" + body + " status code" + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
示例5: test
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
@Test
public void test(TestContext context) throws InterruptedException {
// Async async = context.async();
Vertx vertx = rule.vertx();
WebClient client = WebClient.create(vertx);
HttpRequest<Buffer> req = client.get(41414, "172.21.9.21", "/metrics");
req.putHeader("aa","ccc");
req.timeout(50000);
req.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
System.out.println(response.body());
System.out.println("Received response with status code" + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
// async.complete();
});
System.out.println("here1");
// async.awaitSuccess();
}
示例6: reqOnContext
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
private <T> void reqOnContext(List<Integer> validCodes, HttpMethod method, String path, Query query, String body,
Handler<AsyncResult<T>> resultHandler,
Function<HttpResponse<Buffer>, T> mapper) {
if (query == null) {
query = new Query();
}
if (dc != null) {
query.put("dc", dc);
}
HttpRequest<Buffer> rq = webClient.request(method, path);
query.entrySet().forEach(e -> rq.addQueryParam(e.getKey(), e.getValue()));
if (aclToken != null) {
rq.putHeader(TOKEN_HEADER, aclToken);
}
if (timeoutMs > 0) {
rq.timeout(timeoutMs);
}
rq.sendBuffer(body == null ? Buffer.buffer() : Buffer.buffer(body), h -> {
if (h.succeeded()) {
HttpResponse<Buffer> resp = h.result();
if (validCodes.contains(resp.statusCode())) {
T mapped;
try {
mapped = mapper.apply(resp);
} catch (Throwable throwable) {
resultHandler.handle(Future.failedFuture(throwable));
return;
}
resultHandler.handle(Future.succeededFuture(mapped));
} else {
resultHandler.handle(Future.failedFuture(resp.statusMessage()));
}
} else {
resultHandler.handle(Future.failedFuture(h.cause()));
}
});
}
示例7: testRequestWithResponseContentTypeCheck
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
public void testRequestWithResponseContentTypeCheck(HttpMethod method, String path, int statusCode, String contentType, List<String> acceptableContentTypes) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
HttpRequest<Buffer> request = webClient
.request(method, 8080, "localhost", path);
request.putHeader("Accept", String.join(", ", acceptableContentTypes));
request.send(httpResponseAsyncResult -> {
if (httpResponseAsyncResult.succeeded()) {
assertEquals(httpResponseAsyncResult.result().statusCode(), statusCode);
assertEquals(httpResponseAsyncResult.result().getHeader("content-type"), contentType);
}
latch.countDown();
});
awaitLatch(latch);
}
示例8: getConnectionToken
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
private void getConnectionToken() {
HttpRequest<Buffer> request =restclient
.get(80, "socket.bittrex.com", "/signalr/negotiate")
.addQueryParam("clientProtocol", "1.5")
.addQueryParam("connectionData", "[{\"name\":\"corehub\"}]");
if(isCloudFlareProtected){
request.putHeader("Cookie", headers.get("Cookie"));
}
request.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
if(response.statusCode() == 200){
countTokenError = 0;
JsonObject body = response.bodyAsJsonObject();
System.out.println("Successfully retrieved connection Token");
getLastTicks(tickIntervalStrings.get(5));
setupHttpClient(body.getString("ConnectionToken"), body.getString("ProtocolVersion"));
} else if(response.statusCode()==503 && response.getHeader("Server").equals("cloudflare-nginx") && response.bodyAsString().contains("jschl_vc")){
System.err.println("Negotiation Endpoint is cloudflare protected, trying to bypass");
isCloudFlareProtected = true;
getCloudFlareToken();
} else {
System.err.println("Error while trying to get connection token, retrying in 5: " + response.statusCode());
connectionTokenTimerID = vertx.setTimer(5*1000, id -> {
getConnectionToken();
});
}
} else {
countTokenError++;
if(countTokenError == 5){
countTokenError = 0;
System.err.println("Unable to get connection token, trying with hardcoded Token");
setupHttpClient(hcConnectionToken, hcProtocolVersion);
} else {
System.err.println("Error while trying to get connection token, retrying in 5: " + ar.cause().getMessage());
connectionTokenTimerID = vertx.setTimer(5*1000, id -> {
getConnectionToken();
});
}
}
});
}
示例9: getLastTicks
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
private void getLastTicks(String interval) {
HttpRequest<Buffer> request =restclient
.get(80, "www.bittrex.com", "/Api/v2.0/pub/market/GetTicks")
.addQueryParam("marketName", tradingPair)
.addQueryParam("tickInterval", interval);
if(isCloudFlareProtected){
request.putHeader("Cookie", headers.get("Cookie"));
}
request.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
if(response.statusCode() == 200){
countTokenError = 0;
JsonObject body = response.bodyAsJsonObject();
if(body.containsKey("success") && body.getBoolean("success") == true){
JsonObject payload = new JsonObject();
payload.put("interval", 5);
JsonArray ticks = body.getJsonArray("result");
payload.put("ticks", ticks);
vertx.eventBus().publish(setTicksMessage, payload);
} else {
System.err.println("Error while trying to get Tick Data: "+body.getString("message"));
}
} else {
System.err.println("Error while trying to get ticks, retrying in 5: " + response.statusCode());
tickTimerID = vertx.setTimer(5*1000, id -> {
getLastTicks(interval);
});
}
} else {
countTokenError++;
if(countTickError == 5){
countTickError = 0;
System.err.println("Unable to get Tick Data. Stopping.");
} else {
System.err.println("Unable to get Tick Data, retrying in 5: " + ar.cause().getMessage());
tickTimerID = vertx.setTimer(5*1000, id -> {
getLastTicks(interval);
});
}
}
});
}
示例10: testAuthorizationCodeMode
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
public void testAuthorizationCodeMode() {
Vertx vertx = Vertx.vertx();
OAuth2Auth oauth2 = OAuth2Auth.create(vertx, OAuth2FlowType.AUTH_CODE, new OAuth2ClientOptions()
.setClientID("myClientId")
.setClientSecret("myClientSecret")
.setSite("http://localhost:8080")
.setTokenPath("/oauth/access_token")
.setAuthorizationPath("/oauth/authorize")
);
// when there is a need to access a protected resource or call a protected method,
// call the authZ url for a challenge
String authorization_uri = oauth2.authorizeURL(new JsonObject()
.put("redirect_uri", "http://localhost:8080/secure")
.put("scope", "read"));
WebClient client = WebClient.create(vertx);
HttpRequest<Buffer> request = client.postAbs(authorization_uri);
request.putHeader("Authorization", getHeader());
request.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
String body = response.bodyAsString();
System.out.println("Authorization Code Mode Get Token" + body + " status code" + response.statusCode());
//.put("state", "3(#0/!~"));
// when working with web application use the above string as a redirect url
// in this case GitHub will call you back in the callback uri one should now complete the handshake as:
/*String code = "xxxxxxxxxxxxxxxxxxxxxxxx"; // the code is provided as a url parameter by github callback call
oauth2.getToken(new JsonObject().put("code", code).put("redirect_uri", "http://localhost:8080/secure"), res -> {
if (res.failed()) {
// error, the code provided is not valid
} else {
// save the token and continue...
System.out.println("AuthorizationCode Mode Get Token Info= " + res.result().toString());
}
});*/
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
示例11: sendHeaders2
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
public void sendHeaders2(WebClient client) {
HttpRequest<Buffer> request = client.get(8080, "myserver.mycompany.com", "/some-uri");
request.putHeader("content-type", "application/json");
request.putHeader("other-header", "foo");
}
示例12: addHeaderParam
import io.vertx.ext.web.client.HttpRequest; //导入方法依赖的package包/类
private void addHeaderParam(String headerName, Object value, HttpRequest request) {
request.putHeader(headerName, String.valueOf(value));
}