Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.icore.io.web;
- import groovy.json.StringEscapeUtils;
- import org.activiti.engine.impl.util.json.JSONObject;
- import org.apache.commons.io.IOUtils;
- import org.icore.io.GeneralConfig;
- import org.icore.io.log.sender.EnumCustomLogger;
- import org.icore.io.log.sender.ReturnException;
- import org.icore.util.tool.ToolWeb;
- import org.icore.io.log.sender.LOG;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.HttpEntity;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.MediaType;
- import org.springframework.http.converter.StringHttpMessageConverter;
- import org.springframework.stereotype.Service;
- import org.springframework.web.bind.annotation.RequestMethod;
- import javax.net.ssl.*;
- import java.io.*;
- import java.net.*;
- import java.nio.charset.Charset;
- import java.security.SecureRandom;
- import java.security.cert.X509Certificate;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import static org.icore.util.tool.Tool.sCut;
- import org.slf4j.LoggerFactory;
- import org.springframework.web.client.HttpClientErrorException;
- import org.springframework.web.client.RestTemplate;
- import org.springframework.web.multipart.MultipartFile;
- @Service
- public class HttpRequester {
- //static final transient Logger LOG = LoggerFactory.getLogger(HttpRequester.class);
- //private static final Logger LOG_BIG = LoggerFactory.getLogger("WebBig");
- @Autowired
- GeneralConfig oGeneralConfig;
- private String sLogin;
- private String sPassword;
- private Integer nResponseCode;
- public String getsUser() {
- return sLogin;
- }
- public void setsLogin(String sLogin) {
- this.sLogin = sLogin;
- }
- public String getsPassword() {
- return sPassword;
- }
- public void setsPassword(String sPassword) {
- this.sPassword = sPassword;
- }
- public Integer getnResponseCode() {
- return nResponseCode;
- }
- private final boolean bExceptionOnNorSuccess = true;
- public String postInside(String sURL, Map<String, Object> mParam)
- throws Exception {
- return postInside(sURL, mParam, null, null);
- }
- //для отправки POST запроса с параметрамии в реквесте
- public String postInside(String sURL, Map<String, Object> mParam, Map<String, String> mReqParam, String sParam,
- String contentType) throws Exception {
- sURL = getFullURL(sURL, mReqParam);
- return postInside(sURL, mParam, sParam, contentType);
- }
- public String postInside(String sURL, Map<String, Object> mParam, String sParam, String contentType)
- throws Exception {
- String sLogin, sPassword;
- if (this.sLogin != null) {
- sLogin = this.sLogin;
- } else {
- sLogin = oGeneralConfig.getAuthLogin();
- }
- if (this.sPassword != null) {
- sPassword = this.sPassword;
- } else {
- sPassword = oGeneralConfig.getAuthPassword();
- }
- return postInside(sURL, mParam, sParam, contentType, sLogin, sPassword);
- }
- public String postInside(String sURL, Map<String, Object> mParam, String sParam, String contentType, String sUser, String sPassword)
- throws Exception {
- boolean bSkipValidationSSL = oGeneralConfig.isSimplifySSLConnection();
- simplifySSLConnection(bSkipValidationSSL);
- String saParam = "";
- if (sParam != null) {
- saParam = sParam;
- } else if (mParam != null) {
- for (Map.Entry<String, Object> entry : mParam.entrySet()) {
- if (entry.getValue() != null) {
- String entryValue;
- if (entry.getValue() instanceof String) {
- entryValue = (String) entry.getValue();
- } else {
- entryValue = new JSONObject(entry.getValue()).toString();
- }
- saParam += URLEncoder.encode(entry.getKey(), "UTF-8") + "="
- + URLEncoder.encode(entryValue, "UTF-8") + "&";
- }
- }
- }
- URL oURL = new URL(sURL);
- Integer nStatus = null;
- StringBuilder osReturn = new StringBuilder();
- try {
- HttpURLConnection oConnection = (HttpURLConnection) oURL.openConnection();
- if (sUser != null && sPassword != null) {
- String sAuth = ToolWeb.base64_encode(sUser + ":" + sPassword);
- oConnection.setRequestProperty("authorization", "Basic " + sAuth);
- }
- oConnection.setRequestMethod(RequestMethod.POST.name());
- if (contentType != null && !contentType.equals("null")) {
- oConnection.setRequestProperty("Content-Type", contentType);
- }
- if (contentType == null){
- oConnection.setRequestProperty("Content-Type", "text/plain");
- }
- oConnection.setDoOutput(true);
- // oConnection.setConnectTimeout(5000);//add
- // oConnection.setReadTimeout(5000);
- OutputStreamWriter writer = new OutputStreamWriter(oConnection.getOutputStream(), "UTF-8");
- writer.write(saParam);
- //DataOutputStream writer = new DataOutputStream(oConnection.getOutputStream());
- // Send post request
- //writer.writeBytes(saParam);
- writer.flush();
- writer.close();
- InputStream oInputStream;
- if (oConnection.getResponseCode() >= HttpStatus.BAD_REQUEST.value()) {
- oInputStream = oConnection.getErrorStream();
- } else {
- oInputStream = oConnection.getInputStream();
- }
- BufferedReader oBufferedReader_InputStream = new BufferedReader(new InputStreamReader(oInputStream));
- nStatus = oConnection.getResponseCode();
- this.nResponseCode = nStatus;
- String sLine;
- while ((sLine = oBufferedReader_InputStream.readLine()) != null) {
- osReturn.append(sLine);
- }
- oBufferedReader_InputStream.close();
- LOG.info("FINISHED! (nStatus={},sURL={},saParam(cuted)={},osReturn(cuted)={})", nStatus, sURL, sCut(100, saParam), sCut(100, osReturn.toString())).send();
- LOG.debug("FINISHED! (nStatus={},sURL={},saParam={},osReturn={})", nStatus, sURL, saParam, osReturn)._logger(EnumCustomLogger.LOG_BIG).send();
- } catch (Exception oException) {
- ReturnException.level.error(oException,"BREAKED: {} (sURL={},saParam={})", oException.getMessage(), sURL, saParam).send();
- // new Log(oException, LoggerFactory.getLogger(this.getClass()))
- // ._Case("Web_PostSelf")
- // ._Head("[post]:BREAKED!")
- // ._Body(oException.getMessage())
- //._Status(Log.LogStatus.ERROR)
- //._StatusHTTP(nStatus)
- // ._Param("sURL", sURL)
- // ._Param("saParam", saParam)
- // ._LogTransit()
- // ._LogTrace()
- // .save();
- throw oException; //return null;
- }
- if (nStatus >= HttpStatus.BAD_REQUEST.value()) {
- ReturnException.level.error("Web_PostSelfNo200 [post]:nStatus!=200")._param("nStatus", nStatus)
- ._param("sURL", sURL)
- ._param("saParam", saParam)
- ._param("osReturn", osReturn).send();
- /* new Log(this.getClass(), LoggerFactory.getLogger(this.getClass()))
- ._Case("Web_PostSelfNo200")
- ._Head("[post]:nStatus!=200")
- ._Status(Log.LogStatus.ERROR)
- ._StatusHTTP(nStatus)
- ._Param("nStatus", nStatus)
- ._Param("sURL", sURL)
- ._Param("saParam", saParam)
- ._Param("osReturn", osReturn)
- ._LogTransit()
- .save();*/
- if (bExceptionOnNorSuccess) {
- throw new Exception("nStatus=" + nStatus + "sURL=" + sURL + "saParam=" + saParam + "osReturn=" + osReturn);
- }
- }
- return osReturn.toString();
- }
- public String getInside(String sURL, Map<String, String> mParam) throws Exception {
- return getInside(sURL, mParam, oGeneralConfig.getAuthLogin(), oGeneralConfig.getAuthPassword(), null);
- }
- public String getInside(String sURL, Map<String, String> mParam, String sUser, String sPassword, Map<String, String> mHeaders) throws Exception {
- boolean bSkipValidationSSL = oGeneralConfig.isSimplifySSLConnection();
- simplifySSLConnection(bSkipValidationSSL);
- String requestMethod = RequestMethod.GET.name();
- if (mParam.containsKey("RequestMethod")) {
- requestMethod = mParam.get("RequestMethod");
- mParam.remove("RequestMethod");
- }
- URL oURL = null;
- if (RequestMethod.GET.name().equals(requestMethod)) {
- oURL = new URL(getFullURL(sURL, mParam));
- } else {
- Map<String, String> params = new HashMap<String, String>();
- params.put("sID_Order", mParam.remove("sID_Order"));
- params.put("nID_SubjectMessageType", mParam.remove("nID_SubjectMessageType"));
- params.put("sBody", mParam.remove("sBody"));
- oURL = new URL(getFullURL(sURL, params));
- }
- InputStream oInputStream;
- BufferedReader oBufferedReader_InputStream;
- HttpURLConnection oConnection;
- Integer nStatus;
- StringBuilder osReturn = new StringBuilder();
- try {
- URLConnection oConnectAbstract = oURL.openConnection();
- oConnection = (HttpURLConnection) oConnectAbstract;
- //String sUser = oGeneralConfig.getAuthLogin();
- //String sPassword = oGeneralConfig.getAuthPassword();
- if(sUser != null && sPassword != null){
- String sAuth = ToolWeb.base64_encode(sUser + ":" + sPassword);
- oConnection.setRequestProperty("authorization", "Basic " + sAuth);
- }
- if(mHeaders != null){
- for(String sHeaderType : mHeaders.keySet()){
- oConnection.setRequestProperty(sHeaderType, mHeaders.get(sHeaderType));
- }
- }
- if (RequestMethod.POST.name().equals(requestMethod)) {
- for (Map.Entry<String, String> curr : mParam.entrySet()) {
- oConnection.setRequestProperty(curr.getKey(), StringEscapeUtils.escapeJava(curr.getValue()));
- }
- }
- oConnection.setRequestMethod(requestMethod);
- oConnection.setDoInput(true);
- oConnection.setDoOutput(true);
- // oConnection.setConnectTimeout(5000);//add
- // oConnection.setReadTimeout(5000);
- nStatus = oConnection.getResponseCode();//???
- if (oConnection.getResponseCode() >= HttpStatus.BAD_REQUEST.value()) {
- oInputStream = oConnection.getErrorStream();
- } else {
- oInputStream = oConnection.getInputStream();
- }
- oBufferedReader_InputStream = new BufferedReader(new InputStreamReader(oInputStream));
- String sLine;
- while ((sLine = oBufferedReader_InputStream.readLine()) != null) {
- osReturn.append(sLine);
- }
- oInputStream.close();
- LOG.info("FINISHED! (nStatus={},sURL={},mParam={},osReturn={})", nStatus, sURL, sCut(100, mParam.toString()), sCut(100, osReturn.toString())).send();
- LOG.debug("FINISHED! (nStatus={},sURL={},mParam={},osReturn={})", nStatus, sURL, mParam, osReturn).send();
- } catch (Exception oException) {
- ReturnException.level.error(oException,"Web_GetSelf [get]:BREAKED!")
- ._param("sURL", sURL)
- ._param("mParam", mParam).send();
- /* new Log(oException, LoggerFactory.getLogger(this.getClass()))
- ._Case("Web_GetSelf")
- ._Head("[get]:BREAKED!")
- // ._Body(oException.getMessage())
- ._Status(Log.LogStatus.ERROR)
- //._StatusHTTP(nStatus)
- ._Param("sURL", sURL)
- ._Param("mParam", mParam)
- ._LogTrace()
- .save();*/
- // ReturnException.level.error(oException,"BREAKED: {} (sURL={},mParam={})", oException.getMessage(), sURL, mParam).send();
- throw oException; //return null;
- }
- if (nStatus != 200) {
- ReturnException.level.error("Web_GetSelfNo200 [get]:nStatus!=200")
- ._param("nStatus", nStatus)
- ._param("sURL", sURL)
- ._param("mParam", mParam)
- ._param("osReturn", osReturn).send();
- /* new Log(this.getClass(), LoggerFactory.getLogger(this.getClass()))
- ._Case("Web_GetSelfNo200")
- ._Head("[get]:nStatus!=200")
- ._Status(Log.LogStatus.ERROR)
- //._StatusHTTP(nStatus)
- ._Param("nStatus", nStatus)
- ._Param("sURL", sURL)
- ._Param("mParam", mParam)
- ._Param("osReturn", osReturn)
- .save();*/
- if (bExceptionOnNorSuccess) {
- throw new Exception("nStatus=" + nStatus + "sURL=" + sURL + "mParam=" + mParam + "osReturn=" + osReturn);
- }
- }
- return osReturn.toString();
- }
- /**
- * Method works only with GET http method
- *
- * @param sURL
- * @param mParam
- * @param multipleParam
- * @return
- * @throws Exception
- */
- public String getInside(String sURL, Map<String, String> mParam, Map<String, List<String>> multipleParam) throws Exception {
- sURL = getFullURL(sURL, mParam);
- StringBuilder multipleKeyValues = new StringBuilder();
- for (Map.Entry<String, List<String>> entry : multipleParam.entrySet()) {
- String key = entry.getKey();
- for (String value : entry.getValue()) {
- multipleKeyValues.append("&");
- multipleKeyValues.append(key);
- multipleKeyValues.append("=");
- multipleKeyValues.append(URLEncoder.encode(value, "UTF-8"));
- }
- }
- String mKVs = multipleKeyValues.toString();
- LOG.info("sURL={}", sURL).send();
- LOG.info("multipleKeyValues={}", mKVs).send();
- return getInside(sURL + mKVs, Collections.emptyMap());
- }
- /**
- * Веривикация сертификата при HTTPS-соединении.
- *
- * @param oConnectHTTPS соединение (если null, то верификация будет
- * пропущенна)
- */
- public void simplifySSLConnection(boolean bSkip) {
- System.setProperty("https.protocols", "TLSv1.1");
- if (bSkip) {
- LOG.info("Skip Sertificate!").send();
- TrustManager[] trustAllCerts = {
- new X509TrustManager() {
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- public void checkClientTrusted(X509Certificate[] certs, String authType) {
- }
- public void checkServerTrusted(X509Certificate[] certs, String authType) {
- }
- }
- };
- try {
- SSLContext oSSLContext = SSLContext.getInstance("SSL");
- oSSLContext.init(null, trustAllCerts, new SecureRandom());
- HttpsURLConnection.setDefaultSSLSocketFactory(oSSLContext.getSocketFactory());
- } catch (Exception oException) {
- //_RiseWarn(oException, "simplifySSLConnection", "", "Fail getting SSLContext");
- ReturnException.level.warn(oException,"simplifySSLConnection. Fail getting SSLContext: " + oException.getMessage()).send();
- }
- HostnameVerifier oHostnameVerifier = new HostnameVerifier() {
- public boolean verify(String urlHostName, SSLSession session) {
- //_RiseWarn("simplifySSLConnection", "URL Host(urlHostName)=" + urlHostName, " vs. " + session.getPeerHost());
- ReturnException.level.warn("simplifySSLConnection.(URL Host(urlHostName)=" + urlHostName+ " vs. " + session.getPeerHost() + "): ").send();
- return true;
- }
- };
- HttpsURLConnection.setDefaultHostnameVerifier(oHostnameVerifier);
- }
- }
- public byte[] getInsideBytes(String sURL, Map<String, String> mParam) throws Exception {
- URL oURL = new URL(getFullURL(sURL, mParam));
- InputStream oInputStream;
- byte[] res;
- HttpURLConnection oConnection;
- Integer nStatus;
- try {
- oConnection = (HttpURLConnection) oURL.openConnection();
- String sUser = oGeneralConfig.getAuthLogin();
- String sPassword = oGeneralConfig.getAuthPassword();
- String sAuth = ToolWeb.base64_encode(sUser + ":" + sPassword);
- oConnection.setRequestProperty("authorization", "Basic " + sAuth);
- oConnection.setRequestMethod(RequestMethod.GET.name());
- oConnection.setDoInput(true);
- oConnection.setDoOutput(true);
- // oConnection.setConnectTimeout(5000);//add
- // oConnection.setReadTimeout(5000);
- nStatus = oConnection.getResponseCode();//???
- if (oConnection.getResponseCode() >= HttpStatus.BAD_REQUEST.value()) {
- oInputStream = oConnection.getErrorStream();
- } else {
- oInputStream = oConnection.getInputStream();
- }
- res = IOUtils.toByteArray(oInputStream);
- oInputStream.close();
- LOG.info("FINISHED! (nStatus={},sURL={},mParam={},bytes size={})", nStatus, sURL, sCut(100, mParam.toString()), res.length).send();
- LOG.debug("FINISHED! (nStatus={},sURL={},mParam={},bytes size={})", nStatus, sURL, mParam, res.length).send();
- } catch (Exception oException) {
- ReturnException.level.error(oException,"Web_GetSelf [get]:BREAKED!")
- ._param("sURL", sURL)
- ._param("mParam", mParam).send();
- /*new Log(oException, LoggerFactory.getLogger(this.getClass()))
- ._Case("Web_GetSelf")
- ._Head("[get]:BREAKED!")
- // ._Body(oException.getMessage())
- ._Status(Log.LogStatus.ERROR)
- //._StatusHTTP(nStatus)
- ._Param("sURL", sURL)
- ._Param("mParam", mParam)
- ._LogTrace()
- .save();*/
- //ReturnException.level.error(oException,"BREAKED: {} (sURL={},mParam={})", oException.getMessage(), sURL, mParam).send();
- throw oException; //return null;
- }
- if (nStatus != 200) {
- ReturnException.level.error("Web_GetSelfNo200 [get]:nStatus!=200")
- ._param("nStatus", nStatus)
- ._param("sURL", sURL)
- ._param("mParam", mParam)
- ._param("bytes", res != null ? res.length : "null").send();
- /* new Log(this.getClass(), LoggerFactory.getLogger(this.getClass()))
- ._Case("Web_GetSelfNo200")
- ._Head("[get]:nStatus!=200")
- ._Status(Log.LogStatus.ERROR)
- //._StatusHTTP(nStatus)
- ._Param("nStatus", nStatus)
- ._Param("sURL", sURL)
- ._Param("mParam", mParam)
- ._Param("bytes", res != null ? res.length : "null")
- .save();*/
- if (bExceptionOnNorSuccess) {
- throw new Exception("nStatus=" + nStatus + "sURL=" + sURL + "mParam=" + mParam + "bytes=" + res.length);
- }
- }
- return res;
- }
- public String getFullURL(String sURL, Map<String, String> mParam) throws UnsupportedEncodingException {
- String saParam = "";
- if (mParam != null) {
- for (Map.Entry<String, String> entry : mParam.entrySet()) {
- if (entry.getValue() != null) {
- saParam += entry.getKey() + "="
- + URLEncoder.encode(entry.getValue(), "UTF-8") + "&";
- }
- }
- }
- String sFullURL = sURL;
- if (saParam.length() > 0) {
- sFullURL += "?" + saParam;
- }
- LOG.info("sFullURL {}", sFullURL).send();
- return sFullURL;
- }
- public<T> String postInsideFile(String sURL, T oBody, MediaType oMediaType) {
- RestTemplate restTemplate = new RestTemplate();
- simplifySSLConnection(true);
- String sLogin, sPassword;
- if (this.sLogin != null) {
- sLogin = this.sLogin;
- } else {
- sLogin = oGeneralConfig.getAuthLogin();
- }
- if (this.sPassword != null) {
- sPassword = this.sPassword;
- } else {
- sPassword = oGeneralConfig.getAuthPassword();
- }
- String sAuthorization = String.format("Basic %s", ToolWeb.base64_encode(String.format("%s:%s", "system", "system")));
- LOG.info("sURL: {}, oMediaType: {}, sAuthorization: {}", sURL, oMediaType, sAuthorization).send();
- HttpHeaders headers = new HttpHeaders();
- restTemplate.getMessageConverters()
- .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
- headers.setContentType(oMediaType);
- headers.set("Authorization", sAuthorization);
- HttpEntity<T> entity = new HttpEntity<>(oBody, headers);
- String sReturn = "";
- try {
- sReturn = restTemplate.postForObject(sURL, entity, String.class);
- } catch (HttpClientErrorException e) {
- LOG.info("postInsideFile exception: {}", e).send();
- }
- LOG.info("postInsideFile sReturn: {}", sReturn).send();
- return sReturn;
- }
- public String postRequest(String sURL, MultipartFile oFile, MediaType oMediaType) {
- LOG.info("postRequest started...").send();
- RestTemplate restTemplate = new RestTemplate();
- simplifySSLConnection(true);
- String sLogin, sPassword;
- if (this.sLogin != null) {
- sLogin = this.sLogin;
- } else {
- sLogin = oGeneralConfig.getAuthLogin();
- }
- if (this.sPassword != null) {
- sPassword = this.sPassword;
- } else {
- sPassword = oGeneralConfig.getAuthPassword();
- }
- HttpHeaders headers = new HttpHeaders();
- restTemplate.getMessageConverters()
- .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
- headers.setContentType(oMediaType);
- String sAuthorization = String.format("Basic %s", ToolWeb.base64_encode(String.format("%s:%s", sLogin, sPassword)));
- headers.set("Authorization", sAuthorization);
- HttpEntity<MultipartFile> entity = new HttpEntity<MultipartFile>(oFile , headers);
- String sReturn = restTemplate.postForObject(sURL, entity, String.class);
- LOG.info("Varus postRequest sReturn: {}", sReturn).send();
- return sReturn;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement