List of usage examples for io.netty.handler.codec.http HttpHeaderNames USER_AGENT
AsciiString USER_AGENT
To view the source code for io.netty.handler.codec.http HttpHeaderNames USER_AGENT.
Click Source Link
From source file:ccwihr.client.t1.HttpUploadClient.java
License:Apache License
/** * Standard usage of HTTP API in Netty without file Upload (get is not able * to achieve File upload due to limitation on request size). * * @return the list of headers that will be used in every example after **//*w ww.ja va2s . c om*/ private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // XXX /formget // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue &"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet = new URI(encoder.toString()); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE); headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaderNames.REFERER, uriSimple.toString()); headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); // connection will not close but needed // headers.set("Connection","keep-alive"); // headers.set("Keep-Alive","300"); headers.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); // convert headers to list return headers.entries(); }
From source file:cn.wcl.test.netty.HttpUploadClient.java
License:Apache License
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload * due to limitation on request size).// w w w . j a v a 2s . c o m * * @return the list of headers that will be used in every example after **/ private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // XXX /formget // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue &"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet = new URI(encoder.toString()); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE); headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaderNames.REFERER, uriSimple.toString()); headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); //connection will not close but needed // headers.set("Connection","keep-alive"); // headers.set("Keep-Alive","300"); headers.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); // convert headers to list return headers.entries(); }
From source file:com.bay1ts.bay.core.Request.java
License:Apache License
/** * @return the user-agent//from w w w . j a v a 2 s . c o m */ public String userAgent() { return fullHttpRequest.headers().get(HttpHeaderNames.USER_AGENT); // return fullHttpRequest.getHeader(USER_AGENT); }
From source file:com.phei.netty.nio.http.upload.HttpUploadClient.java
License:Apache License
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload * due to limitation on request size)./*from w w w . j ava 2 s .c o m*/ * * @return the list of headers that will be used in every example after **/ private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // XXX /formget // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue &"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet = new URI(encoder.toString()); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE); headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaderNames.REFERER, uriSimple.toString()); headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); //connection will not close but needed // headers.set("Connection","keep-alive"); headers.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request List<Entry<String, String>> entries = headers.entriesConverted(); channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
From source file:com.vmware.dcp.common.http.netty.NettyHttpServiceClient.java
License:Open Source License
private void sendRequest(Operation op) { if (!checkScheme(op)) { return;/*from w w w.j a va2 s. c o m*/ } try { byte[] body = Utils.encodeBody(op); String pathAndQuery; String path = op.getUri().getPath(); String query = op.getUri().getQuery(); path = path == null || path.isEmpty() ? "/" : path; if (query != null) { pathAndQuery = path + "?" + query; } else { pathAndQuery = path; } if (this.httpProxy != null) { pathAndQuery = op.getUri().toString(); } HttpRequest request = null; HttpMethod method = HttpMethod.valueOf(op.getAction().toString()); if (body == null || body.length == 0) { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery); } else { ByteBuf content = Unpooled.wrappedBuffer(body); request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery, content); } for (Entry<String, String> nameValue : op.getRequestHeaders().entrySet()) { request.headers().set(nameValue.getKey(), nameValue.getValue()); } request.headers().set(HttpHeaderNames.CONTENT_LENGTH, Long.toString(op.getContentLength())); request.headers().set(HttpHeaderNames.CONTENT_TYPE, op.getContentType()); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); if (op.getContextId() != null) { request.headers().set(Operation.CONTEXT_ID_HEADER, op.getContextId()); } if (op.getReferer() != null) { request.headers().set(Operation.REFERER_HEADER, op.getReferer().toString()); } if (op.getCookies() != null) { String header = CookieJar.encodeCookies(op.getCookies()); request.headers().set(HttpHeaderNames.COOKIE, header); } request.headers().set(HttpHeaderNames.USER_AGENT, this.userAgent); request.headers().set(HttpHeaderNames.ACCEPT, Operation.MEDIA_TYPE_APPLICATION_JSON); request.headers().set(HttpHeaderNames.HOST, op.getUri().getHost() + ((op.getUri().getPort() != -1) ? (":" + op.getUri().getPort()) : "")); op.nestCompletion((o, e) -> { if (e != null) { fail(e, op); return; } // After request is sent control is transferred to the // NettyHttpServerResponseHandler. The response handler will nest completions // and call complete() when response is received, which will invoke this completion op.complete(); }); op.getSocketContext().writeHttpRequest(request); } catch (Throwable e) { op.setBody(ServiceErrorResponse.create(e, Operation.STATUS_CODE_BAD_REQUEST, EnumSet.of(ErrorDetail.SHOULD_RETRY))); fail(e, op); } }
From source file:com.vmware.xenon.common.http.netty.NettyHttpServiceClient.java
License:Open Source License
private void doSendRequest(Operation op) { final Object originalBody = op.getBodyRaw(); try {/*from ww w . j a v a2 s . c o m*/ byte[] body = Utils.encodeBody(op); if (op.getContentLength() > getRequestPayloadSizeLimit()) { stopTracking(op); Exception e = new IllegalArgumentException("Content-Length " + op.getContentLength() + " is greater than max size allowed " + getRequestPayloadSizeLimit()); op.setBody(ServiceErrorResponse.create(e, Operation.STATUS_CODE_BAD_REQUEST)); op.fail(e); return; } String pathAndQuery; String path = op.getUri().getPath(); String query = op.getUri().getRawQuery(); String userInfo = op.getUri().getRawUserInfo(); path = path == null || path.isEmpty() ? "/" : path; if (query != null) { pathAndQuery = path + "?" + query; } else { pathAndQuery = path; } /** * NOTE: Pay close attention to calls that access the operation request headers, since * they will cause a memory allocation. We avoid the allocation by first checking if * the operation has any custom headers to begin with, then we check for the specific * header */ boolean hasRequestHeaders = op.hasRequestHeaders(); boolean useHttp2 = op.isConnectionSharing(); if (this.httpProxy != null || useHttp2 || userInfo != null) { pathAndQuery = op.getUri().toString(); } NettyFullHttpRequest request = null; HttpMethod method = HttpMethod.valueOf(op.getAction().toString()); if (body == null || body.length == 0) { request = new NettyFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery, Unpooled.buffer(0), false); } else { ByteBuf content = Unpooled.wrappedBuffer(body, 0, (int) op.getContentLength()); request = new NettyFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery, content, false); } if (useHttp2) { // when operation is cloned, it may contain original streamId header. remove it. if (hasRequestHeaders) { op.getRequestHeaders().remove(Operation.STREAM_ID_HEADER); } // We set the operation so that once a streamId is assigned, we can record // the correspondence between the streamId and operation: this will let us // handle responses properly later. request.setOperation(op); } String pragmaHeader = op.getRequestHeader(Operation.PRAGMA_HEADER); if (op.isFromReplication() && pragmaHeader == null) { request.headers().set(HttpHeaderNames.PRAGMA, Operation.PRAGMA_DIRECTIVE_REPLICATED); } if (op.getTransactionId() != null) { request.headers().set(Operation.TRANSACTION_ID_HEADER, op.getTransactionId()); } if (op.getContextId() != null) { request.headers().set(Operation.CONTEXT_ID_HEADER, op.getContextId()); } AuthorizationContext ctx = op.getAuthorizationContext(); if (ctx != null && ctx.getToken() != null) { request.headers().set(Operation.REQUEST_AUTH_TOKEN_HEADER, ctx.getToken()); } boolean isXenonToXenon = op.isFromReplication(); boolean isRequestWithCallback = false; if (hasRequestHeaders) { for (Entry<String, String> nameValue : op.getRequestHeaders().entrySet()) { String key = nameValue.getKey(); if (!isXenonToXenon) { if (Operation.REQUEST_CALLBACK_LOCATION_HEADER.equals(key)) { isRequestWithCallback = true; isXenonToXenon = true; } else if (Operation.RESPONSE_CALLBACK_STATUS_HEADER.equals(key)) { isXenonToXenon = true; } } request.headers().set(nameValue.getKey(), nameValue.getValue()); } } request.headers().set(HttpHeaderNames.CONTENT_LENGTH, Long.toString(op.getContentLength())); request.headers().set(HttpHeaderNames.CONTENT_TYPE, op.getContentType()); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); if (!isXenonToXenon) { if (op.getCookies() != null) { String header = CookieJar.encodeCookies(op.getCookies()); request.headers().set(HttpHeaderNames.COOKIE, header); } if (op.hasReferer()) { request.headers().set(HttpHeaderNames.REFERER, op.getRefererAsString()); } request.headers().set(HttpHeaderNames.USER_AGENT, this.userAgent); if (op.getRequestHeader(Operation.ACCEPT_HEADER) == null) { request.headers().set(HttpHeaderNames.ACCEPT, Operation.MEDIA_TYPE_EVERYTHING_WILDCARDS); } request.headers().set(HttpHeaderNames.HOST, op.getUri().getHost()); } boolean doCookieJarUpdate = !isXenonToXenon; boolean stopTracking = !isRequestWithCallback; op.nestCompletion((o, e) -> { if (e != null) { fail(e, op, originalBody); return; } if (stopTracking) { stopTracking(op); } if (doCookieJarUpdate) { updateCookieJarFromResponseHeaders(o); } // After request is sent control is transferred to the // NettyHttpServerResponseHandler. The response handler will nest completions // and call complete() when response is received, which will invoke this completion op.complete(); }); op.getSocketContext().writeHttpRequest(request); } catch (Throwable e) { op.setBody(ServiceErrorResponse.create(e, Operation.STATUS_CODE_BAD_REQUEST, EnumSet.of(ErrorDetail.SHOULD_RETRY))); fail(e, op, originalBody); } }
From source file:de.ocarthon.core.network.HttpClient.java
License:Apache License
public synchronized String postRequest(String query, List<Map.Entry<String, String>> postParameters, String filePostName, String fileName, ByteBuf fileData, String mime) { if (bootstrap == null) { setupBootstrap();//from www .j a va2 s . co m } if (channel == null || forceReconnect) { ChannelFuture cf = bootstrap.connect(host, port); forceReconnect = false; cf.awaitUninterruptibly(); channel = cf.channel(); channel.pipeline().addLast("handler", new SimpleChannelInboundHandler<HttpObject>() { @Override protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse response = ((HttpResponse) msg); String connection = (String) response.headers().get(HttpHeaderNames.CONNECTION); if (connection != null && connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString())) forceReconnect = true; } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; String message = chunk.content().toString(CharsetUtil.UTF_8); if (!message.isEmpty()) { result[0] = message; synchronized (result) { result.notify(); } } } } }); } boolean isFileAttached = fileData != null && fileData.isReadable(); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, scheme + "://" + host + ":" + port + "/" + query); HttpPostRequestEncoder bodyReqEncoder; try { bodyReqEncoder = new HttpPostRequestEncoder(httpDataFactory, request, isFileAttached); for (Map.Entry<String, String> entry : postParameters) { bodyReqEncoder.addBodyAttribute(entry.getKey(), entry.getValue()); } if (isFileAttached) { if (mime == null) mime = "application/octet-stream"; MixedFileUpload mfu = new MixedFileUpload(filePostName, fileName, mime, "binary", null, fileData.capacity(), DefaultHttpDataFactory.MINSIZE); mfu.addContent(fileData, true); bodyReqEncoder.addBodyHttpData(mfu); } HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); headers.set(HttpHeaderNames.USER_AGENT, "OcarthonCore HttpClient"); request = bodyReqEncoder.finalizeRequest(); } catch (Exception e) { throw new NullPointerException("key or value is empty or null"); } channel.write(request); if (bodyReqEncoder.isChunked()) { channel.write(bodyReqEncoder); } channel.flush(); synchronized (result) { try { result.wait(); } catch (InterruptedException e) { return null; } } return result[0]; }
From source file:discord4j.rest.http.client.DiscordWebClient.java
License:Open Source License
/** * Create a new {@link DiscordWebClient} wrapping HTTP, Discord and encoding/decoding resources. * * @param httpClient a Reactor Netty HTTP client * @param exchangeStrategies a strategy to transform requests and responses * @param token a Discord token for API authorization *///from w w w . j av a 2 s. c o m public DiscordWebClient(HttpClient httpClient, ExchangeStrategies exchangeStrategies, String token) { final Properties properties = GitProperties.getProperties(); final String version = properties.getProperty(GitProperties.APPLICATION_VERSION, "3"); final String url = properties.getProperty(GitProperties.APPLICATION_URL, "https://discord4j.com"); final HttpHeaders defaultHeaders = new DefaultHttpHeaders(); defaultHeaders.add(HttpHeaderNames.CONTENT_TYPE, "application/json"); defaultHeaders.add(HttpHeaderNames.AUTHORIZATION, "Bot " + token); defaultHeaders.add(HttpHeaderNames.USER_AGENT, "DiscordBot(" + url + ", " + version + ")"); this.httpClient = httpClient; this.defaultHeaders = defaultHeaders; this.exchangeStrategies = exchangeStrategies; }
From source file:Netty4.book.http.upload.HttpUploadClient.java
License:Apache License
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload * due to limitation on request size)./* w w w . j av a2 s .co m*/ * * @return the list of headers that will be used in every example after **/ private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // XXX /formget // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue &"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet = new URI(encoder.toString()); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE); headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaderNames.REFERER, uriSimple.toString()); headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); //connection will not close but needed // headers.set("Connection","keep-alive"); // headers.set("Keep-Alive","300"); headers.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request List<Entry<String, String>> entries = headers.entries(); channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
From source file:org.ballerinalang.net.grpc.stubs.AbstractStub.java
License:Open Source License
private void setOutboundUserAgent(HttpHeaders headers) { String userAgent;// w ww .j a v a 2 s . c o m if (CACHE_BALLERINA_VERSION != null) { userAgent = "ballerina/" + CACHE_BALLERINA_VERSION; } else { userAgent = "ballerina"; } if (!headers.contains(HttpHeaderNames.USER_AGENT)) { // If User-Agent is not already set from program headers.set(HttpHeaderNames.USER_AGENT, userAgent); } }