cokr.xit.foundation.web.Http 추가

master
mjkhan21 2 years ago
parent 1556ce7ad6
commit 1c5556c038

@ -0,0 +1,293 @@
package cokr.xit.foundation.web;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import cokr.xit.foundation.AbstractComponent;
/**Http
* <p> .
* <pre><code> new Http().get(
* "https://...",
* new Http.Conf()
* // .header("Content-Type", "application/x-www-form-urlencoded")
* .param("param0", "value0")
* .param("param1", "value1")
* .onResponse(resp -> System.out.println(resp));
* );</code></pre>
* @author mjkhan
*/
public class Http extends AbstractComponent {
/**http
* @author mjkhan
*/
public static class Conf {
private String charset;
private String url;
private String method;
private LinkedHashMap<String, String>
params,
headers;
private int timeout;
private Consumer<Response> handler = System.out::println;
/** .
* @return
*/
protected String charset() {
return ifEmpty(charset, () -> "UTF-8");
}
/** .
* @param charset
* @return Conf
*/
public Conf charset(String charset) {
this.charset = charset;
return this;
}
/**http URL .
* @return URL
* @throws Exception
*/
protected URL url() throws Exception {
return new URL(url);
}
/**http . "GET"
* @return http
*/
protected String method() {
return ifEmpty(method, "GET");
}
/** .
* @return
*/
protected String params() {
return !isEmpty(params) ? params.entrySet().stream().map(this::encode).collect(Collectors.joining("&")) : "";
}
/** .
* @param entry
* @return
*/
protected String encode(Map.Entry<String, String> entry) {
try {
return URLEncoder.encode(entry.getKey(), charset()) + "=" + URLEncoder.encode(entry.getValue(), charset());
} catch (Exception e) {
throw runtimeException(e);
}
}
/** .
* @param name
* @param value
* @return
*/
public Conf param(String name, String value) {
if (params == null)
params = new LinkedHashMap<>();
params.put(name, value);
return this;
}
/** .
* @param name
* @param value
* @return
*/
public Conf header(String name, String value) {
if (headers == null)
headers = new LinkedHashMap<>();
headers.put(name, value);
return this;
}
/** http .
* @param http HttpURLConnection
*/
protected void setHeaders(HttpURLConnection http) {
if (isEmpty(headers)) return;
headers.forEach(http::setRequestProperty);
}
/**http . 10000
* @return http
*/
protected int timeout() {
return Math.max(timeout, 10000);
}
/**http .
* @param timeout http
* @return Conf
*/
public Conf timeout(int timeout) {
this.timeout = timeout;
return this;
}
/**http .
* @param handler http
* @return Conf
*/
public Conf onResponse(Consumer<Response> handler) {
this.handler = handler;
return this;
}
}
/**http
* @author mjkhan
*/
public static class Response {
private int status;
private String response;
/**http .
* @return http
*/
public int getStatus() {
return status;
}
/**http .
* @return
* <ul><li> true</li>
* <li> false</li>
* </ul>
*/
public boolean isSuccess() {
return status <= 299;
}
/**http .
* @return http
*/
public String getResponse() {
return response;
}
@Override
public String toString() {
return String.format("status: %d, success: %s, response: %s", status, isSuccess(), response);
}
}
/** url GET .
* @param url url
* @param conf
*/
public void get(String url, Conf conf) {
if (conf == null)
conf = new Conf();
conf.method = "GET";
request(url, conf);
}
/** url POST .
* @param url url
* @param conf
*/
public void post(String url, Conf conf) {
if (conf == null)
conf = new Conf();
conf.method = "POST";
request(url, conf);
}
/** url , conf .
* @param url url
* @param conf
*/
protected void request(String url, Conf conf) {
HttpURLConnection http = null;
try {
conf.url = url;
http = (HttpURLConnection)conf.url().openConnection();
http.setRequestMethod(conf.method());
http.setUseCaches(false);
conf.setHeaders(http);
http.setConnectTimeout(conf.timeout());
http.setReadTimeout(conf.timeout());
setParams(conf, http);
Response resp = getResponse(http);
if (conf.handler != null)
conf.handler.accept(resp);
} catch (Exception e) {
if (conf.handler != null) {
conf.handler.accept(getResponse(e));
}
} finally {
if (http != null)
http.disconnect();
}
}
/**http .
* @param conf Http.Conf
* @param http HttpURLConnection
* @throws Exception
*/
protected void setParams(Conf conf, HttpURLConnection http) throws Exception {
String params = conf.params();
if (!isEmpty(params)) {
http.setDoOutput(true);
DataOutputStream out = new DataOutputStream(http.getOutputStream());
out.writeBytes(params);
out.flush();
out.close();
}
}
/**http .
* @param http HttpURLConnection
* @return http
* @throws Exception
*/
protected Response getResponse(HttpURLConnection http) throws Exception {
Response resp = new Response();
resp.status = http.getResponseCode();
try (
InputStream input = resp.isSuccess() ? http.getInputStream() : http.getErrorStream();
InputStreamReader inputStreamReader = new InputStreamReader(input);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
) {
String str = "";
StringBuilder buff = new StringBuilder();
while ((str = bufferedReader.readLine()) != null) {
buff.append(str);
}
resp.response = buff.toString();
return resp;
} catch (Exception e) {
return getResponse(e);
}
}
/**http .
* @param t Throwable
* @return http
*/
protected Response getResponse(Throwable t) {
Response resp = new Response();
resp.status = 500;
resp.response = rootCause(t).getMessage();
return resp;
}
}
Loading…
Cancel
Save