Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 23.96 KB | None | 0 0
  1. package org.icore.io.web;
  2.  
  3. import groovy.json.StringEscapeUtils;
  4. import org.activiti.engine.impl.util.json.JSONObject;
  5. import org.apache.commons.io.IOUtils;
  6. import org.icore.io.GeneralConfig;
  7. import org.icore.io.log.sender.EnumCustomLogger;
  8. import org.icore.io.log.sender.ReturnException;
  9. import org.icore.util.tool.ToolWeb;
  10. import org.icore.io.log.sender.LOG;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.http.HttpEntity;
  13. import org.springframework.http.HttpHeaders;
  14. import org.springframework.http.HttpStatus;
  15. import org.springframework.http.MediaType;
  16. import org.springframework.http.converter.StringHttpMessageConverter;
  17. import org.springframework.stereotype.Service;
  18. import org.springframework.web.bind.annotation.RequestMethod;
  19.  
  20. import javax.net.ssl.*;
  21. import java.io.*;
  22. import java.net.*;
  23. import java.nio.charset.Charset;
  24. import java.security.SecureRandom;
  25. import java.security.cert.X509Certificate;
  26. import java.util.Collections;
  27. import java.util.HashMap;
  28. import java.util.List;
  29. import java.util.Map;
  30.  
  31. import static org.icore.util.tool.Tool.sCut;
  32. import org.slf4j.LoggerFactory;
  33. import org.springframework.web.client.HttpClientErrorException;
  34. import org.springframework.web.client.RestTemplate;
  35. import org.springframework.web.multipart.MultipartFile;
  36.  
  37. @Service
  38. public class HttpRequester {
  39.  
  40.     //static final transient Logger LOG = LoggerFactory.getLogger(HttpRequester.class);
  41.     //private static final Logger LOG_BIG = LoggerFactory.getLogger("WebBig");
  42.  
  43.     @Autowired
  44.     GeneralConfig oGeneralConfig;
  45.  
  46.     private String sLogin;
  47.     private String sPassword;
  48.     private Integer nResponseCode;
  49.  
  50.     public String getsUser() {
  51.         return sLogin;
  52.     }
  53.  
  54.     public void setsLogin(String sLogin) {
  55.         this.sLogin = sLogin;
  56.     }
  57.  
  58.     public String getsPassword() {
  59.         return sPassword;
  60.     }
  61.  
  62.     public void setsPassword(String sPassword) {
  63.         this.sPassword = sPassword;
  64.     }
  65.  
  66.     public Integer getnResponseCode() {
  67.         return nResponseCode;
  68.     }
  69.  
  70.     private final boolean bExceptionOnNorSuccess = true;
  71.  
  72.     public String postInside(String sURL, Map<String, Object> mParam)
  73.             throws Exception {
  74.         return postInside(sURL, mParam, null, null);
  75.     }
  76.  
  77.     //для отправки POST запроса с параметрамии в реквесте
  78.     public String postInside(String sURL, Map<String, Object> mParam, Map<String, String> mReqParam, String sParam,
  79.                              String contentType) throws Exception {
  80.         sURL = getFullURL(sURL, mReqParam);
  81.         return postInside(sURL, mParam, sParam, contentType);
  82.     }
  83.  
  84.     public String postInside(String sURL, Map<String, Object> mParam, String sParam, String contentType)
  85.             throws Exception {
  86.         String sLogin, sPassword;
  87.         if (this.sLogin != null) {
  88.             sLogin = this.sLogin;
  89.         } else {
  90.             sLogin = oGeneralConfig.getAuthLogin();
  91.         }
  92.         if (this.sPassword != null) {
  93.             sPassword = this.sPassword;
  94.         } else {
  95.             sPassword = oGeneralConfig.getAuthPassword();
  96.         }
  97.         return postInside(sURL, mParam, sParam, contentType, sLogin, sPassword);
  98.     }
  99.  
  100.     public String postInside(String sURL, Map<String, Object> mParam, String sParam, String contentType, String sUser, String sPassword)
  101.             throws Exception {
  102.  
  103.         boolean bSkipValidationSSL = oGeneralConfig.isSimplifySSLConnection();
  104.         simplifySSLConnection(bSkipValidationSSL);
  105.  
  106.         String saParam = "";
  107.         if (sParam != null) {
  108.             saParam = sParam;
  109.         } else if (mParam != null) {
  110.             for (Map.Entry<String, Object> entry : mParam.entrySet()) {
  111.                 if (entry.getValue() != null) {
  112.                     String entryValue;
  113.                     if (entry.getValue() instanceof String) {
  114.                         entryValue = (String) entry.getValue();
  115.                     } else {
  116.                         entryValue = new JSONObject(entry.getValue()).toString();
  117.                     }
  118.                     saParam += URLEncoder.encode(entry.getKey(), "UTF-8") + "="
  119.                             + URLEncoder.encode(entryValue, "UTF-8") + "&";
  120.                 }
  121.             }
  122.         }
  123.  
  124.         URL oURL = new URL(sURL);
  125.         Integer nStatus = null;
  126.         StringBuilder osReturn = new StringBuilder();
  127.         try {
  128.             HttpURLConnection oConnection = (HttpURLConnection) oURL.openConnection();
  129.            
  130.             if (sUser != null && sPassword != null) {
  131.                 String sAuth = ToolWeb.base64_encode(sUser + ":" + sPassword);
  132.                 oConnection.setRequestProperty("authorization", "Basic " + sAuth);
  133.             }
  134.  
  135.             oConnection.setRequestMethod(RequestMethod.POST.name());
  136.             if (contentType != null && !contentType.equals("null")) {
  137.                 oConnection.setRequestProperty("Content-Type", contentType);
  138.             }
  139.            
  140.             if (contentType == null){
  141.                 oConnection.setRequestProperty("Content-Type", "text/plain");
  142.             }
  143.  
  144.             oConnection.setDoOutput(true);
  145.            // oConnection.setConnectTimeout(5000);//add
  146.            // oConnection.setReadTimeout(5000);
  147.            
  148.             OutputStreamWriter writer = new OutputStreamWriter(oConnection.getOutputStream(), "UTF-8");
  149.             writer.write(saParam);
  150.             //DataOutputStream writer = new DataOutputStream(oConnection.getOutputStream());
  151.             // Send post request
  152.             //writer.writeBytes(saParam);
  153.             writer.flush();
  154.             writer.close();
  155.  
  156.             InputStream oInputStream;
  157.             if (oConnection.getResponseCode() >= HttpStatus.BAD_REQUEST.value()) {
  158.                 oInputStream = oConnection.getErrorStream();
  159.             } else {
  160.                 oInputStream = oConnection.getInputStream();
  161.             }
  162.             BufferedReader oBufferedReader_InputStream = new BufferedReader(new InputStreamReader(oInputStream));
  163.             nStatus = oConnection.getResponseCode();
  164.             this.nResponseCode = nStatus;
  165.             String sLine;
  166.  
  167.             while ((sLine = oBufferedReader_InputStream.readLine()) != null) {
  168.                 osReturn.append(sLine);
  169.             }
  170.             oBufferedReader_InputStream.close();
  171.  
  172.             LOG.info("FINISHED! (nStatus={},sURL={},saParam(cuted)={},osReturn(cuted)={})", nStatus, sURL, sCut(100, saParam), sCut(100, osReturn.toString())).send();
  173.             LOG.debug("FINISHED! (nStatus={},sURL={},saParam={},osReturn={})", nStatus, sURL, saParam, osReturn)._logger(EnumCustomLogger.LOG_BIG).send();
  174.         } catch (Exception oException) {
  175.             ReturnException.level.error(oException,"BREAKED: {} (sURL={},saParam={})", oException.getMessage(), sURL, saParam).send();
  176. //            new Log(oException, LoggerFactory.getLogger(this.getClass()))
  177. //                    ._Case("Web_PostSelf")
  178. //                    ._Head("[post]:BREAKED!")
  179.                     //                    ._Body(oException.getMessage())
  180.                     //._Status(Log.LogStatus.ERROR)
  181.                     //._StatusHTTP(nStatus)
  182. //                    ._Param("sURL", sURL)
  183. //                    ._Param("saParam", saParam)
  184. //                    ._LogTransit()
  185. //                    ._LogTrace()
  186. //                    .save();
  187.             throw oException; //return null;
  188.         }
  189.         if (nStatus >= HttpStatus.BAD_REQUEST.value()) {
  190.             ReturnException.level.error("Web_PostSelfNo200 [post]:nStatus!=200")._param("nStatus", nStatus)
  191.                     ._param("sURL", sURL)
  192.                     ._param("saParam", saParam)
  193.                     ._param("osReturn", osReturn).send();
  194.  
  195. /*            new Log(this.getClass(), LoggerFactory.getLogger(this.getClass()))
  196.                     ._Case("Web_PostSelfNo200")
  197.                     ._Head("[post]:nStatus!=200")
  198.                     ._Status(Log.LogStatus.ERROR)
  199.                     ._StatusHTTP(nStatus)
  200.                     ._Param("nStatus", nStatus)
  201.                     ._Param("sURL", sURL)
  202.                     ._Param("saParam", saParam)
  203.                     ._Param("osReturn", osReturn)
  204.                     ._LogTransit()
  205.                     .save();*/
  206.             if (bExceptionOnNorSuccess) {
  207.                 throw new Exception("nStatus=" + nStatus + "sURL=" + sURL + "saParam=" + saParam + "osReturn=" + osReturn);
  208.             }
  209.         }
  210.         return osReturn.toString();
  211.     }
  212.  
  213.     public String getInside(String sURL, Map<String, String> mParam) throws Exception {
  214.         return getInside(sURL, mParam, oGeneralConfig.getAuthLogin(), oGeneralConfig.getAuthPassword(), null);
  215.     }
  216.    
  217.     public String getInside(String sURL, Map<String, String> mParam, String sUser, String sPassword, Map<String, String> mHeaders) throws Exception {
  218.  
  219.         boolean bSkipValidationSSL = oGeneralConfig.isSimplifySSLConnection();
  220.         simplifySSLConnection(bSkipValidationSSL);
  221.  
  222.         String requestMethod = RequestMethod.GET.name();
  223.         if (mParam.containsKey("RequestMethod")) {
  224.             requestMethod = mParam.get("RequestMethod");
  225.             mParam.remove("RequestMethod");
  226.         }
  227.         URL oURL = null;
  228.         if (RequestMethod.GET.name().equals(requestMethod)) {
  229.             oURL = new URL(getFullURL(sURL, mParam));
  230.         } else {
  231.             Map<String, String> params = new HashMap<String, String>();
  232.             params.put("sID_Order", mParam.remove("sID_Order"));
  233.             params.put("nID_SubjectMessageType", mParam.remove("nID_SubjectMessageType"));
  234.             params.put("sBody", mParam.remove("sBody"));
  235.             oURL = new URL(getFullURL(sURL, params));
  236.         }
  237.         InputStream oInputStream;
  238.         BufferedReader oBufferedReader_InputStream;
  239.         HttpURLConnection oConnection;
  240.  
  241.         Integer nStatus;
  242.         StringBuilder osReturn = new StringBuilder();
  243.         try {
  244.  
  245.             URLConnection oConnectAbstract = oURL.openConnection();
  246.             oConnection = (HttpURLConnection) oConnectAbstract;
  247.            
  248.             //String sUser = oGeneralConfig.getAuthLogin();
  249.             //String sPassword = oGeneralConfig.getAuthPassword();
  250.            
  251.             if(sUser != null && sPassword != null){
  252.                 String sAuth = ToolWeb.base64_encode(sUser + ":" + sPassword);
  253.                 oConnection.setRequestProperty("authorization", "Basic " + sAuth);
  254.             }
  255.            
  256.             if(mHeaders != null){
  257.                 for(String sHeaderType : mHeaders.keySet()){
  258.                     oConnection.setRequestProperty(sHeaderType, mHeaders.get(sHeaderType));
  259.                 }
  260.             }
  261.             if (RequestMethod.POST.name().equals(requestMethod)) {
  262.                 for (Map.Entry<String, String> curr : mParam.entrySet()) {
  263.                     oConnection.setRequestProperty(curr.getKey(), StringEscapeUtils.escapeJava(curr.getValue()));
  264.                 }
  265.             }
  266.  
  267.             oConnection.setRequestMethod(requestMethod);
  268.             oConnection.setDoInput(true);
  269.             oConnection.setDoOutput(true);
  270.           //  oConnection.setConnectTimeout(5000);//add
  271.           //  oConnection.setReadTimeout(5000);
  272.             nStatus = oConnection.getResponseCode();//???
  273.             if (oConnection.getResponseCode() >= HttpStatus.BAD_REQUEST.value()) {
  274.                 oInputStream = oConnection.getErrorStream();
  275.             } else {
  276.                 oInputStream = oConnection.getInputStream();
  277.             }
  278.             oBufferedReader_InputStream = new BufferedReader(new InputStreamReader(oInputStream));
  279.             String sLine;
  280.             while ((sLine = oBufferedReader_InputStream.readLine()) != null) {
  281.                 osReturn.append(sLine);
  282.             }
  283.             oInputStream.close();
  284.  
  285.             LOG.info("FINISHED! (nStatus={},sURL={},mParam={},osReturn={})", nStatus, sURL, sCut(100, mParam.toString()), sCut(100, osReturn.toString())).send();
  286.             LOG.debug("FINISHED! (nStatus={},sURL={},mParam={},osReturn={})", nStatus, sURL, mParam, osReturn).send();
  287.  
  288.         } catch (Exception oException) {
  289.             ReturnException.level.error(oException,"Web_GetSelf [get]:BREAKED!")
  290.                     ._param("sURL", sURL)
  291.                     ._param("mParam", mParam).send();
  292.  
  293. /*                            new Log(oException, LoggerFactory.getLogger(this.getClass()))
  294.                     ._Case("Web_GetSelf")
  295.                     ._Head("[get]:BREAKED!")
  296.                     //                    ._Body(oException.getMessage())
  297.                     ._Status(Log.LogStatus.ERROR)
  298.                     //._StatusHTTP(nStatus)
  299.                     ._Param("sURL", sURL)
  300.                     ._Param("mParam", mParam)
  301.                     ._LogTrace()
  302.                     .save();*/
  303. //            ReturnException.level.error(oException,"BREAKED: {} (sURL={},mParam={})", oException.getMessage(), sURL, mParam).send();
  304.             throw oException; //return null;
  305.         }
  306.         if (nStatus != 200) {
  307.             ReturnException.level.error("Web_GetSelfNo200 [get]:nStatus!=200")
  308.                     ._param("nStatus", nStatus)
  309.                     ._param("sURL", sURL)
  310.                     ._param("mParam", mParam)
  311.                     ._param("osReturn", osReturn).send();
  312.  
  313. /*                    new Log(this.getClass(), LoggerFactory.getLogger(this.getClass()))
  314.                     ._Case("Web_GetSelfNo200")
  315.                     ._Head("[get]:nStatus!=200")
  316.                     ._Status(Log.LogStatus.ERROR)
  317.                     //._StatusHTTP(nStatus)
  318.                     ._Param("nStatus", nStatus)
  319.                     ._Param("sURL", sURL)
  320.                     ._Param("mParam", mParam)
  321.                     ._Param("osReturn", osReturn)
  322.                     .save();*/
  323.             if (bExceptionOnNorSuccess) {
  324.                 throw new Exception("nStatus=" + nStatus + "sURL=" + sURL + "mParam=" + mParam + "osReturn=" + osReturn);
  325.             }
  326.         }
  327.         return osReturn.toString();
  328.     }
  329.  
  330.     /**
  331.      * Method works only with GET http method
  332.      *
  333.      * @param sURL
  334.      * @param mParam
  335.      * @param multipleParam
  336.      * @return
  337.      * @throws Exception
  338.      */
  339.     public String getInside(String sURL, Map<String, String> mParam, Map<String, List<String>> multipleParam) throws Exception {
  340.         sURL = getFullURL(sURL, mParam);
  341.         StringBuilder multipleKeyValues = new StringBuilder();
  342.         for (Map.Entry<String, List<String>> entry : multipleParam.entrySet()) {
  343.             String key = entry.getKey();
  344.             for (String value : entry.getValue()) {
  345.                 multipleKeyValues.append("&");
  346.                 multipleKeyValues.append(key);
  347.                 multipleKeyValues.append("=");
  348.                 multipleKeyValues.append(URLEncoder.encode(value, "UTF-8"));
  349.             }
  350.         }
  351.         String mKVs = multipleKeyValues.toString();
  352.         LOG.info("sURL={}", sURL).send();
  353.         LOG.info("multipleKeyValues={}", mKVs).send();
  354.         return getInside(sURL + mKVs, Collections.emptyMap());
  355.     }
  356.  
  357.     /**
  358.      * Веривикация сертификата при HTTPS-соединении.
  359.      *
  360.      * @param oConnectHTTPS соединение (если null, то верификация будет
  361.      * пропущенна)
  362.      */
  363.     public void simplifySSLConnection(boolean bSkip) {
  364.         System.setProperty("https.protocols", "TLSv1.1");
  365.         if (bSkip) {
  366.             LOG.info("Skip Sertificate!").send();
  367.             TrustManager[] trustAllCerts = {
  368.                 new X509TrustManager() {
  369.                     public X509Certificate[] getAcceptedIssuers() {
  370.                         return null;
  371.                     }
  372.  
  373.                     public void checkClientTrusted(X509Certificate[] certs, String authType) {
  374.                     }
  375.  
  376.                     public void checkServerTrusted(X509Certificate[] certs, String authType) {
  377.                     }
  378.                 }
  379.             };
  380.             try {
  381.                 SSLContext oSSLContext = SSLContext.getInstance("SSL");
  382.                 oSSLContext.init(null, trustAllCerts, new SecureRandom());
  383.                 HttpsURLConnection.setDefaultSSLSocketFactory(oSSLContext.getSocketFactory());
  384.                 } catch (Exception oException) {
  385.                 //_RiseWarn(oException, "simplifySSLConnection", "", "Fail getting SSLContext");
  386.                 ReturnException.level.warn(oException,"simplifySSLConnection. Fail getting SSLContext: " + oException.getMessage()).send();
  387.             }
  388.             HostnameVerifier oHostnameVerifier = new HostnameVerifier() {
  389.                 public boolean verify(String urlHostName, SSLSession session) {
  390.                     //_RiseWarn("simplifySSLConnection", "URL Host(urlHostName)=" + urlHostName, " vs. " + session.getPeerHost());
  391.                     ReturnException.level.warn("simplifySSLConnection.(URL Host(urlHostName)=" + urlHostName+ " vs. " + session.getPeerHost() + "): ").send();
  392.                     return true;
  393.                 }
  394.             };
  395.             HttpsURLConnection.setDefaultHostnameVerifier(oHostnameVerifier);
  396.  
  397.         }
  398.     }
  399.  
  400.     public byte[] getInsideBytes(String sURL, Map<String, String> mParam) throws Exception {
  401.         URL oURL = new URL(getFullURL(sURL, mParam));
  402.         InputStream oInputStream;
  403.         byte[] res;
  404.         HttpURLConnection oConnection;
  405.         Integer nStatus;
  406.         try {
  407.  
  408.             oConnection = (HttpURLConnection) oURL.openConnection();
  409.            
  410.             String sUser = oGeneralConfig.getAuthLogin();
  411.             String sPassword = oGeneralConfig.getAuthPassword();
  412.             String sAuth = ToolWeb.base64_encode(sUser + ":" + sPassword);
  413.             oConnection.setRequestProperty("authorization", "Basic " + sAuth);
  414.  
  415.             oConnection.setRequestMethod(RequestMethod.GET.name());
  416.             oConnection.setDoInput(true);
  417.             oConnection.setDoOutput(true);
  418.           //  oConnection.setConnectTimeout(5000);//add
  419.           //  oConnection.setReadTimeout(5000);
  420.             nStatus = oConnection.getResponseCode();//???
  421.             if (oConnection.getResponseCode() >= HttpStatus.BAD_REQUEST.value()) {
  422.                 oInputStream = oConnection.getErrorStream();
  423.             } else {
  424.                 oInputStream = oConnection.getInputStream();
  425.             }
  426.             res = IOUtils.toByteArray(oInputStream);
  427.             oInputStream.close();
  428.  
  429.             LOG.info("FINISHED! (nStatus={},sURL={},mParam={},bytes size={})", nStatus, sURL, sCut(100, mParam.toString()), res.length).send();
  430.             LOG.debug("FINISHED! (nStatus={},sURL={},mParam={},bytes size={})", nStatus, sURL, mParam, res.length).send();
  431.  
  432.         } catch (Exception oException) {
  433.             ReturnException.level.error(oException,"Web_GetSelf [get]:BREAKED!")
  434.                     ._param("sURL", sURL)
  435.                     ._param("mParam", mParam).send();
  436.  
  437.                     /*new Log(oException, LoggerFactory.getLogger(this.getClass()))
  438.                     ._Case("Web_GetSelf")
  439.                     ._Head("[get]:BREAKED!")
  440.                     //                    ._Body(oException.getMessage())
  441.                     ._Status(Log.LogStatus.ERROR)
  442.                     //._StatusHTTP(nStatus)
  443.                     ._Param("sURL", sURL)
  444.                     ._Param("mParam", mParam)
  445.                     ._LogTrace()
  446.                     .save();*/
  447.             //ReturnException.level.error(oException,"BREAKED: {} (sURL={},mParam={})", oException.getMessage(), sURL, mParam).send();
  448.             throw oException; //return null;
  449.         }
  450.         if (nStatus != 200) {
  451.             ReturnException.level.error("Web_GetSelfNo200 [get]:nStatus!=200")
  452.                     ._param("nStatus", nStatus)
  453.                     ._param("sURL", sURL)
  454.                     ._param("mParam", mParam)
  455.                     ._param("bytes", res != null ? res.length : "null").send();
  456. /*            new Log(this.getClass(), LoggerFactory.getLogger(this.getClass()))
  457.                     ._Case("Web_GetSelfNo200")
  458.                     ._Head("[get]:nStatus!=200")
  459.                     ._Status(Log.LogStatus.ERROR)
  460.                     //._StatusHTTP(nStatus)
  461.                     ._Param("nStatus", nStatus)
  462.                     ._Param("sURL", sURL)
  463.                     ._Param("mParam", mParam)
  464.                     ._Param("bytes", res != null ? res.length : "null")
  465.                     .save();*/
  466.             if (bExceptionOnNorSuccess) {
  467.                 throw new Exception("nStatus=" + nStatus + "sURL=" + sURL + "mParam=" + mParam + "bytes=" + res.length);
  468.             }
  469.         }
  470.         return res;
  471.     }
  472.  
  473.     public String getFullURL(String sURL, Map<String, String> mParam) throws UnsupportedEncodingException {
  474.         String saParam = "";
  475.         if (mParam != null) {
  476.             for (Map.Entry<String, String> entry : mParam.entrySet()) {
  477.                 if (entry.getValue() != null) {
  478.                     saParam += entry.getKey() + "="
  479.                             + URLEncoder.encode(entry.getValue(), "UTF-8") + "&";
  480.                 }
  481.             }
  482.         }
  483.  
  484.         String sFullURL = sURL;
  485.         if (saParam.length() > 0) {
  486.             sFullURL += "?" + saParam;
  487.         }
  488.        
  489.         LOG.info("sFullURL {}", sFullURL).send();
  490.         return sFullURL;
  491.     }
  492.     public<T> String postInsideFile(String sURL, T oBody, MediaType oMediaType) {
  493.         RestTemplate restTemplate = new RestTemplate();
  494.         simplifySSLConnection(true);
  495.         String sLogin, sPassword;
  496.         if (this.sLogin != null) {
  497.             sLogin = this.sLogin;
  498.         } else {
  499.             sLogin = oGeneralConfig.getAuthLogin();
  500.         }
  501.         if (this.sPassword != null) {
  502.             sPassword = this.sPassword;
  503.         } else {
  504.             sPassword = oGeneralConfig.getAuthPassword();
  505.         }
  506.         String sAuthorization = String.format("Basic %s", ToolWeb.base64_encode(String.format("%s:%s", "system", "system")));
  507.         LOG.info("sURL: {}, oMediaType: {}, sAuthorization: {}", sURL, oMediaType, sAuthorization).send();
  508.         HttpHeaders headers = new HttpHeaders();
  509.         restTemplate.getMessageConverters()
  510.                 .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
  511.         headers.setContentType(oMediaType);
  512.         headers.set("Authorization", sAuthorization);
  513.         HttpEntity<T> entity = new HttpEntity<>(oBody, headers);
  514.  
  515.         String sReturn = "";
  516.  
  517.         try {
  518.             sReturn = restTemplate.postForObject(sURL, entity, String.class);
  519.         } catch (HttpClientErrorException e) {
  520.             LOG.info("postInsideFile exception: {}", e).send();
  521.         }
  522.  
  523.         LOG.info("postInsideFile sReturn: {}", sReturn).send();
  524.         return sReturn;
  525.     }
  526.  
  527.     public String postRequest(String sURL, MultipartFile oFile, MediaType oMediaType) {
  528.         LOG.info("postRequest started...").send();
  529.         RestTemplate restTemplate = new RestTemplate();
  530.         simplifySSLConnection(true);
  531.         String sLogin, sPassword;
  532.         if (this.sLogin != null) {
  533.             sLogin = this.sLogin;
  534.         } else {
  535.             sLogin = oGeneralConfig.getAuthLogin();
  536.         }
  537.         if (this.sPassword != null) {
  538.             sPassword = this.sPassword;
  539.         } else {
  540.             sPassword = oGeneralConfig.getAuthPassword();
  541.         }
  542.         HttpHeaders headers = new HttpHeaders();
  543.         restTemplate.getMessageConverters()
  544.                 .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
  545.         headers.setContentType(oMediaType);
  546.         String sAuthorization = String.format("Basic %s", ToolWeb.base64_encode(String.format("%s:%s", sLogin, sPassword)));
  547.         headers.set("Authorization", sAuthorization);
  548.         HttpEntity<MultipartFile> entity = new HttpEntity<MultipartFile>(oFile , headers);
  549.         String sReturn = restTemplate.postForObject(sURL, entity, String.class);
  550.         LOG.info("Varus postRequest sReturn: {}", sReturn).send();
  551.         return sReturn;
  552.     }
  553. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement