Java tutorial
/** * Copyright 20151121 Hxms. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package org.server.core.netty.http; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.cookie.ClientCookieEncoder; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory; import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder; import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder.ErrorDataEncoderException; import io.netty.util.CharsetUtil; import java.io.File; import java.net.URI; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.server.tools.SystemUtil; /** * * netty http * * @author Hxms * */ public class NHttpRequestParams { // Force to use memory-based data. final static DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false); URI uri; HttpMethod method = HttpMethod.GET; HttpVersion version = HttpVersion.HTTP_1_1; String userAgent = "Dalvik/1.6.0 (Linux; U)"; Map<String, String> form, headers; Map<String, File> uploadFormFile; boolean multipart; Cookie[] cookies; int connectTimeout = 3000, requestTimeout = 10000, retryConnectCount = 3; NHttpRequestCallback callback; Charset responseCharset = CharsetUtil.UTF_8; private NHttpRequestParams(URI uri) { this.uri = uri; } /** * ? * * @return ? */ public URI uri() { return uri; } /** * @return the version */ public HttpVersion version() { return version; } /** * @param version * the version to set */ public NHttpRequestParams version(HttpVersion version) { this.version = version; return this; } /** * @return the method */ public HttpMethod method() { return method; } /** * @param method * the method to set */ public NHttpRequestParams method(HttpMethod method) { this.method = method; return this; } /** * * * @param name * ?? * @param value * */ public void header(String name, String value) { if (this.headers == null) headers(new HashMap<String, String>()); this.headers.put(name, value); } /** * ? Https * * @return ? SSL */ public boolean https() { return uri.getScheme().equalsIgnoreCase("https"); } /** * ??? * * @return the form ? */ public Map<String, String> form() { return form; } /** * ??? * * @param form * the form to set ????? */ public NHttpRequestParams form(Map<String, String> form) { this.form = form; return this; } /** * ? * * @param name * ?? * @param value * */ public void form(String name, String value) { if (this.form == null) this.form = new HashMap<String, String>(); this.form.put(name, value); } /** * * * @param name * ?? * @param value * */ public boolean uploadFile(String name, File value) { if (!value.exists() || !value.isFile()) return false; if (this.uploadFormFile == null) this.uploadFormFile = new HashMap<String, File>(); this.uploadFormFile.put(name, value); return true; } /** * True if the FORM is a ENCTYPE="multipart/form-data" * * @return the multipart */ public boolean multipart() { return multipart; } /** * True if the FORM is a ENCTYPE="multipart/form-data" * * @param multipart * the multipart to set */ public void multipart(boolean multipart) { this.multipart = multipart; } /** * ? * * @return the headers ? */ public Map<String, String> headers() { return headers; } /** * ? * * @param headers * the headers to set ? */ public NHttpRequestParams headers(Map<String, String> headers) { this.headers = headers; return this; } /** * Cookie * * @return the cookies */ public Cookie[] cookies() { return cookies; } /** * Cookie * * @param cookies * the cookies to set Cookie */ public NHttpRequestParams cookies(Cookie[] cookies) { this.cookies = cookies; return this; } /** * * * * @return the callback */ public NHttpRequestCallback callback() { return callback; } /** * * * * @param callback * the callback to set */ public NHttpRequestParams callback(NHttpRequestCallback callback) { this.callback = callback; return this; } /** * * socket * * @return the connectTimeout */ public int connectTimeout() { return connectTimeout; } /** * * * * @param connectTimeout * the connectTimeout to set */ public NHttpRequestParams connectTimeout(int connectTimeout) { this.connectTimeout = Math.max(connectTimeout, 1); return this; } /** * * * * @return the requestTimeout */ public int requestTimeout() { return requestTimeout; } /** * * * * @param requestTimeout * the requestTimeout to set */ public NHttpRequestParams requestTimeout(int requestTimeout) { this.requestTimeout = requestTimeout; return this; } /** * ?? * * @return the responseCharset */ public Charset responseCharset() { return responseCharset; } /** * ? * * @param responseCharset * the responseCharset to set ?? */ public NHttpRequestParams responseCharset(Charset responseCharset) { this.responseCharset = responseCharset; return this; } /** * * user agent * * @return the userAgent */ public String userAgent() { return userAgent; } /** * * user agent * * @param userAgent * the userAgent to set */ public NHttpRequestParams userAgent(String userAgent) { this.userAgent = userAgent; return this; } /** * * ? * * @return the retryConnectCount */ public int retryConnectCount() { return retryConnectCount; } /** * * ? * * @param retryConnectCount * the retryConnectCount to set */ public NHttpRequestParams retryConnectCount(int retryConnectCount) { this.retryConnectCount = Math.max(retryConnectCount, 0); return this; } /** * ? * * @return ? */ protected String hostname() { return uri.getHost(); } /** * ? * * @return ? */ protected int port() { return uri.getPort() == -1 ? https() ? 443 : 80 : uri.getPort(); } /** * ? * * @return * @throws ErrorDataEncoderException * post ? */ Object[] getFormObject(HttpRequest request) throws ErrorDataEncoderException { boolean formNoneEntity = form == null || form.isEmpty(); boolean uploadFileNoneEntity = uploadFormFile == null || uploadFormFile.isEmpty(); if (formNoneEntity && uploadFileNoneEntity) return null; HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(inMemoryFactory, request, multipart); if (!formNoneEntity) { for (Entry<String, String> item : form.entrySet()) { encoder.addBodyAttribute(item.getKey(), item.getValue()); } } if (!uploadFileNoneEntity) { for (Entry<String, File> item : uploadFormFile.entrySet()) { encoder.addBodyFileUpload(item.getKey(), item.getValue(), headers != null ? headers.get(HttpHeaders.Names.CONTENT_TYPE) : null, false); } } return new Object[] { encoder.finalizeRequest(), encoder }; } /** * http * * @return * @throws ErrorDataEncoderException * post ? */ protected Object[] buildRequest() throws ErrorDataEncoderException { // handler the uri String requestUri = null; String path = uri.getRawPath(); String query = uri.getRawQuery(); URI uri = this.uri; // concat uri if (query == null || query == "") requestUri = path; else requestUri = String.format("%s?%s", path, query); // create new path uri = URI.create(requestUri); // create request DefaultFullHttpRequest request = new DefaultFullHttpRequest(version, method, uri.toASCIIString()); buildRequestHeaders(request); // encoder post Object[] finalRequest = getFormObject(request); // if encoder is null if (finalRequest == null) { return new HttpObject[] { request }; } else { return finalRequest; } } private void buildRequestHeaders(DefaultFullHttpRequest request) { // config request header request.headers().set(HttpHeaders.Names.HOST, this.uri.getHost()); // request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, "gzip, deflate"); // added user agent if (userAgent != null && !userAgent.isEmpty()) request.headers().set(HttpHeaders.Names.USER_AGENT, userAgent); else request.headers().remove(HttpHeaders.Names.USER_AGENT); // add custom if (this.headers != null) { for (Entry<String, String> item : this.headers.entrySet()) { request.headers().set(item.getKey(), item.getValue()); } } // add cookie if (this.cookies != null) { String cookieValue = ClientCookieEncoder.STRICT.encode(cookies); request.headers().set(HttpHeaders.Names.COOKIE, cookieValue); } } /** * ? * * @param uri * ? * @return ? */ public static NHttpRequestParams create(URI uri) { return new NHttpRequestParams(uri); } /** * ? * * @param uri * ? * @return ? */ public static NHttpRequestParams create(String uri) { return new NHttpRequestParams(URI.create(uri)); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); try { Object[] httpObjects = buildRequest(); for (int i = 0; i < httpObjects.length; i++) if (httpObjects[i] != null) stringBuilder.append(httpObjects[i].toString()).append(SystemUtil.LINE_SEPARATOR); } catch (Throwable e) { } return stringBuilder.toString(); } }