org.zodiac.sdk.nio.channeling.http.HttpRequestBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zodiac-sdk-nio Show documentation
Show all versions of zodiac-sdk-nio Show documentation
Zodiac SDK NIO2(New Non-Blocking IO)
package org.zodiac.sdk.nio.channeling.http;
import org.zodiac.sdk.nio.http.common.HttpRequestMethod;
import org.zodiac.sdk.nio.http.common.HttpHeaders;
import org.zodiac.sdk.nio.http.common.HttpProtocolVersion;
public class HttpRequestBuilder {
private HttpRequestMethod method;
private String path = "";
private String args = "";
private StringBuilder headersBuilder = new StringBuilder();
private String body = null;
public HttpRequestBuilder() {
}
public void setMethod(HttpRequestMethod method) {
this.method = method;
}
public void setPath(String path) {
this.path = path;
}
public void setArgs(String args) {
if (args == null || args.isEmpty()) {
return;
}
if (!args.startsWith("?")) {
this.args = '?' + args;
} else {
this.args = args;
}
}
public void addHeader(HttpHeaders httpHeaders) {
if (null == httpHeaders) {
return;
}
httpHeaders.forEach((name, valueList) -> {
this.headersBuilder.append(name).append(": ").append(valueList.get(0)).append("\r\n");
});
}
public void addHeader(String key, String value) {
if (null == key) {
return;
}
if (value.contains("\r\n")) {
value = value.replace("\r\n", "");
} else if (value.contains("\n")) {
value = value.replace("\n", "");
}
this.headersBuilder.append(key).append(": ").append(value).append("\r\n");
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
StringBuilder buildRequest = new StringBuilder();
if (method == null) {
method = HttpRequestMethod.GET;
}
if (args == null) {
args = "";
}
buildRequest
.append(method.name()).append(' ')
.append(path).append(args.replace(' ', '+')).append(' ')
.append(HttpProtocolVersion.HTTP_1_1.getText() + "\r\n")
.append(headersBuilder.toString()).append("\r\n")
;
if (body != null) {
buildRequest.append(body);
}
return buildRequest.toString();
}
public HttpRequestMethod getMethod() {
return method;
}
public String getPath() {
return path;
}
public String getArgs() {
return args;
}
public StringBuilder getHeadersBuilder() {
return headersBuilder;
}
public String getBody() {
return body;
}
}