com.baidu.haotianjing.core.http.HttpRequest Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of haotianjing-java-sdk Show documentation
Show all versions of haotianjing-java-sdk Show documentation
Haotianjing SaaS SDK for Java
The newest version!
package com.baidu.haotianjing.core.http;
import com.baidu.haotianjing.core.utils.UrlUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.HashMap;
import java.util.Map;
/**
* 业务请求对象转成的具体HTTP Client请求对象
*/
public final class HttpRequest {
private String protocol;
private String domain;
private String url;
private Map headers = new HashMap<>();
private Map queryParams = new HashMap<>();
private byte[] body;
public HttpRequest protocol(String protocol) {
this.protocol = protocol;
return this;
}
public HttpRequest domain(String domain) {
this.domain = domain;
return this;
}
public HttpRequest url(String url) {
this.url = url;
return this;
}
public HttpRequest headers(Map headers) {
this.headers = headers;
return this;
}
public HttpRequest header(String key, String value) {
headers.put(key, value);
return this;
}
public HttpRequest queryParams(Map queryParams) {
this.queryParams = queryParams;
return this;
}
public HttpRequest queryParam(String key, String value) {
queryParams.put(key, value);
return this;
}
public HttpRequest body(byte[] body) {
this.body = body;
return this;
}
public byte[] getBody() {
return body;
}
/**
* 根据protocol、domain、path、querys组装完整请求URL
*/
public String assembleUrl() {
StringBuilder sb = new StringBuilder();
sb.append(protocol);
sb.append("://");
sb.append(domain);
sb.append(url);
if (-1 == sb.indexOf("?")) {
sb.append("?");
} else if (!sb.toString().endsWith("?")) {
sb.append("&");
}
if (queryParams.size() > 0) {
sb.append(UrlUtils.encode(queryParams));
}
String url = sb.toString();
if (url.endsWith("?") || url.endsWith("&")) {
url = url.substring(0, url.length() - 1);
}
return url;
}
@Override
public String toString() {
return ReflectionToStringBuilder.
toString(this, ToStringStyle.MULTI_LINE_STYLE, true, true);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy