Groovy Örnek 1: Gövde içerisinde gelen bir değeri Başlık alanına kopyalamak

import  java.lang.String;

int start=requestBodyTextFromClient.indexOf("access_token")+16;
int end=requestBodyTextFromClient.indexOf("\"",start+1);
String token=requestBodyTextFromClient.substring(start,end);
requestHeaderMapToTargetAPI.put("authorization",token);
GROOVY

Groovy Örnek 2: Rest Api Call

import groovy.json.JsonSlurper

def location = 'Stockholm, Sweden'
def connection = new URL( "https://query.yahooapis.com/v1/public/yql?q=" +
        URLEncoder.encode(
                "select item " +
                        "from weather.forecast where woeid in " +
                        "(select woeid from geo.places(1) " +
                        "where text='$location')",
                'UTF-8' ) )
        .openConnection() as HttpURLConnection

// set some headers
connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
connection.setRequestProperty( 'Accept', 'application/json' )

if ( connection.responseCode == 200 ) {
    // get the JSON response
    def json = connection.inputStream.withCloseable { inStream ->
        new JsonSlurper().parse( inStream as InputStream )
    }

    // extract some data from the JSON, printing a report
    def item = json.query.results.channel.item
   	
    requestHeaderMapToTargetAPI.put("title" ,item.title)     
    requestHeaderMapToTargetAPI.put("Temperature" , "${item.condition?.temp}")
    requestHeaderMapToTargetAPI.put("Condition", "${item.condition?.text}")

    requestUrlParamMapToTargetAPI.put("title" ,item.title)     
    requestUrlParamMapToTargetAPI.put("Temperature" , "${item.condition?.temp}")
    requestUrlParamMapToTargetAPI.put("Condition", "${item.condition?.text}")

      bodyText= 'title:'+ item.title + ', temp:' + "${item.condition?.temp}" +", text:" + "${item.condition?.text}"
      
    // show some forecasts
    def forecast= 'Forecasts:'
    item.forecast.each { f ->
        forecast += ' * ${f.date} - Low: ${f.low}, High: ${f.high}, Condition: ${f.text}'
    }
} else {
  	requestHeaderMapToTargetAPI.put("responseCode" ,connection.responseCode)
    requestHeaderMapToTargetAPI.put("responseText" ,connection.inputStream.text)
      
    requestUrlParamMapToTargetAPI.put("responseCode" ,connection.responseCode)
    requestUrlParamMapToTargetAPI.put("responseText" ,connection.inputStream.text)
    
      bodyText='title:'+ item.title + ', code:' + connection.responseCode +", text:" + connection.inputStream.text
}
GROOVY


Groovy Örnek 3: Rest Api Call - x-www-form-urlencoded

import groovy.json.JsonSlurper

try{
String urlParameters="url=parametreleri&burada=yerAlacak";
byte[] postData = urlParameters.getBytes( "UTF-8" );
int postDataLength = postData.length;

String request = "http://1.1.1.1:30080/token";

URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setUseCaches(false);
try{
   DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
   wr.write( postData );
   wr.close();
}catch(Exception e){
requestErrorMessageToTargetAPI=e.getMessage();
}
def json = conn.inputStream.withCloseable { inStream ->
        new JsonSlurper().parse( inStream as InputStream )
}
requestHeaderMapToTargetAPI.put("Authorization" ,"Bearer "+json.access_token)   
}
catch(Exception e){
requestErrorMessageToTargetAPI=e.getMessage();
}
GROOVY

Groovy Örnek 4: Soap mesaj gönderme

import groovy.util.XmlSlurper
 
URL url = new URL("https://servis.apinizer.com/SoapExampleService.svc");
HttpURLConnection conn = url.openConnection();
conn.setDoOutput(true);
var password='''<![CDATA[ ]]>''';
 
conn.setRequestProperty( "SOAPAction", "http://tempuri.org/SoapExampleService/GetToken" );
conn.setRequestProperty( "Content-Type", "text/xml" );
var xml="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">   <soapenv:Header/>   <soapenv:Body>      <tem:GetToken>         <tem:userName>kullaniciAdi</tem:userName>         <tem:password>"+password+"</tem:password>      </tem:GetToken>   </soapenv:Body></soapenv:Envelope>";
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(xml);
wr.close();
  
InputStream  responseStream = conn.getInputStream();
String response = responseStream.getText("utf-8");
responseStream.close();
 
def Envelope = new XmlSlurper().parseText(response);
requestHeaderMapToTargetAPI.put( "TokenId", Envelope.Body.GetTokenResponse.GetTokenResult.text() );

GROOVY

Groovy Örnek 5: Gövde içerisinde gelen json değerleri bozmadan alan eklemek

import groovy.json.JsonSlurper;
import groovy.json.JsonOutput;

def jsonSlurper = new JsonSlurper()

def jsonMessage = jsonSlurper.parseText(requestBodyTextFromClient)

jsonMessage.put("kisiId","1111");

requestBodyTextFromClient=JsonOutput.toJson(jsonMessage);
/* requestHeaderMapFromClient.remove("Authorization"); */
GROOVY

Groovy Örnek 6: Json Gelen Mesaj üzerinden Mail Atma

import javax.mail.*
import javax.mail.internet.*
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
 
 /*
    Request:
    {
      "gonderen":"bilgi.apinizer",
      "alicilar":"info@apinizer.com",
      "bilgiAlicilar":null,
      "gizliAlicilar":null,
      "konu":"test",
      "icerik":"test",
      "icerikTuru":"text/html;charset=utf-8"
    }
     
    Response:
    {
      "islemBasariliMi":true,
      "hataMesaji":"",
      "hataKodu":""
    }
 */
  
try {
   
    requestHeaderMapFromClient.put('statusCode',0);
 
    def jsonSlurper = new JsonSlurper()
    def jsonMessage = jsonSlurper.parseText(requestBodyTextFromClient)
  
 
    String from=jsonMessage.gonderen ;
    if(from.equals("bilgi.apinizer")){
        from="info@apinizer.com";
    }else if(from.equals("apinizer.hata")){
        from="warning@apinizer.com";
    }
    else{
          
        statusCode=400;
        requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: false, hataMesaji: 'Hatalı gönderen bilgisi', hataKodu:'01-ERR-02'])
        return;
    } 
 
 
    String to=jsonMessage.alicilar;
    String cc=jsonMessage.bilgiAlicilar;
    String bcc=jsonMessage.bilgiAlicilar;
 
    if(!to?.trim()&& !cc?.trim()&&  !bcc?.trim()){
        requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: false, hataMesaji: 'En az bir alıcı eklenmeli', hataKodu:'01-ERR-03'])
        statusCode=400;
        return;
    }
 
    String subject=jsonMessage.konu;
    if(subject?.trim()){
        subject=""
    }
 
    String content=jsonMessage.icerik;
    if(content?.trim()){
        content=""
    }
 
    String mimeType=jsonMessage.icerikTuru;
    if(mimeType?.trim()){
        mimeType="text/html;charset=utf-8"
    }
 
    // Init constants of sender email account.
    String email = "apinizer.hata"
    String password = ""
    String host = "mail.apinizer.com"
    String port = "25" //  "465" "587"
 
    // Set up properties.
    Properties props = System.getProperties()
    props.put("mail.smtp.user", email)
    props.put("mail.smtp.host", host)
    props.put("mail.smtp.port", port)
    props.put("mail.smtp.auth", "false")
    props.put("mail.smtp.starttls.enable","false")
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
    props.put("mail.smtp.ssl.trust", host) // Change host to "*" if you want to trust all host.
 
    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(email, password);
            }
        });
         
    // Set up message.
    MimeMessage message = new MimeMessage(session)
    message.setFrom(new InternetAddress(from))
    if(to?.trim()){
        message.addRecipients(Message.RecipientType.TO, new InternetAddress(to))
    }
    if(cc?.trim()){
        message.addRecipients(Message.RecipientType.CC, new InternetAddress(cc))
    }
    if(bcc?.trim()){
        message.addRecipients(Message.RecipientType.BCC, new InternetAddress(bcc))
    }
    message.setSubject(subject)
    message.setContent(content, mimeType)
 
    try {
        // Send mail.
        Transport.send(message )
    } catch (MessagingException e) {
        e.printStackTrace();
        statusCode=500;
        requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: false, hataMesaji: 'Mail gönderirken hata oluştu:' + e.getMessage(), hataKodu:'01-ERR-04'])
        return;
    }
    statusCode=200;
    requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: true, hataMesaji: '', hataKodu:''])
 
} catch (MessagingException e) {
    e.printStackTrace();
    statusCode=500;
    requestErrorMessageFromClient = JsonOutput.toJson([islemBasariliMi: false, hataMesaji: 'Mail gönderirken hata oluştu:' + e.getMessage(), hataKodu:'01-ERR-05'])
    return;
}
GROOVY

Groovy Örnek 7: Soap Gelen Mesaj üzerinden Mail Atma

import javax.mail.*
import org.apache.commons.lang3.StringUtils
import javax.mail.internet.*
import groovy.util.XmlSlurper
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
   
 /*
REQUEST SAMPLE
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://schema.apinizer.com/Yardimci/EPosta/v1">
    <soapenv:Header/>
    <soapenv:Body>
      <v1:EPostaGonder>
         <!--Optional:-->
         <v1:ePostaBilgisi>
            <!--Optional:-->
            <v1:Alicilar>
               <!--Zero or more repetitions:-->
               <v1:mailAdresi>info@apinizer.com</v1:mailAdresi>
            </v1:Alicilar>
            <!--Optional:-->
            <v1:BilgiAlicilar>
               <!--Zero or more repetitions:-->
               <v1:mailAdresi></v1:mailAdresi>
            </v1:BilgiAlicilar>
            <!--Optional:-->
            <v1:GizliBilgiAlicilar>
               <!--Zero or more repetitions:-->
               <v1:mailAdresi></v1:mailAdresi>
            </v1:GizliBilgiAlicilar>
            <v1:Gonderen>support@apinizer.com</v1:Gonderen>
            <v1:Icerik>Örnek içerik</v1:Icerik>
            <v1:Konu>Örnek Konu adı</v1:Konu>
            <v1:MesajTuru>text/html;charset=utf-8</v1:MesajTuru>
         </v1:ePostaBilgisi>
      </v1:EPostaGonder>
    </soapenv:Body>
</soapenv:Envelope>
   
RESPONSE SAMPLE
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
      <out:EPostaGonderResponse xmlns:out="http://schema.apinizer.com/Yardimci/EPosta/v1">
         <out:EPostaGonderResult>
            <out:IslemBasariliMi>true</out:IslemBasariliMi>
         </out:EPostaGonderResult>
      </out:EPostaGonderResponse>
    </soapenv:Body>
</soapenv:Envelope>
 */
    
def createSoapResponse( def IslemBasariliMi, def HataMesaji, def HataKodu){
   
    def builder = new StreamingMarkupBuilder()
    builder.encoding ='utf-8'
    def soapRequest = builder.bind {
        mkp.declareNamespace( 'soapenv': "http://schemas.xmlsoap.org/soap/envelope/" )
         mkp.declareNamespace( 'out': "http://schema.apinizer.com/Yardimci/EPosta/v1")
          mkp.declareNamespace( 'xsi': "http://www.w3.org/2001/XMLSchema-instance" )
            
        'soapenv:Envelope' {
            'soapenv:Header'()
            'soapenv:Body' {      
                'out.EPostaGonderResponse' ( ){
                    'out.EPostaGonderResult' ( ){
                        'out.IslemBasariliMi'(IslemBasariliMi)
                        if(!IslemBasariliMi){
                            'out.HataMesaji'(HataMesaji)
                            'out.HataKodu'(HataKodu)
                        }
                    }
                }
            }
        }
    }
    return XmlUtil.serialize(soapRequest)
}
     
try {
    requestHeaderMapFromClient.put('statusCodeToTargetAPI',0);
    def Envelope = new XmlSlurper().parseText(requestBodyTextFromClient);
    def ePostaBilgisi=  Envelope.Body.EPostaGonder.ePostaBilgisi;
      
    String to="";
    int toSize=ePostaBilgisi.Alicilar.mailAdresi.size();
    for(int i=0;i<toSize;i++){
        to+=ePostaBilgisi.Alicilar.mailAdresi[i].text()+",";
    }
    to= StringUtils.removeEnd(to, ",");
       
    String cc="";
    int ccSize=ePostaBilgisi.BilgiAlicilar.mailAdresi.size();
    for(int i=0;i<ccSize;i++){
        cc+=ePostaBilgisi.BilgiAlicilar.mailAdresi[i].text()+",";
    }
    cc= StringUtils.removeEnd(to, ",");
       
    String bcc="";
    int bccSize=ePostaBilgisi.GizliBilgiAlicilar.mailAdresi.size();
    for(int i=0;i<bccSize;i++){
        bcc+=ePostaBilgisi.GizliBilgiAlicilar.mailAdresi[i].text()+",";
    }
    bcc= StringUtils.removeEnd(to, ",");
    String from=ePostaBilgisi.Gonderen.text() ;
    if(!from?.trim()){
        requestErrorMessageToTargetAPI = createSoapResponse(false,'En az bir kimden bilgisi eklenmeli!','01-ERR-03' );
        statusCodeToTargetAPI=400;
        return;
    }
       
    if(!to?.trim()&& !cc?.trim()&&  !bcc?.trim()){
        requestErrorMessageToTargetAPI = createSoapResponse(false,'En az bir alıcı eklenmeli!','01-ERR-04' );
        statusCodeToTargetAPI=400;
        return;
    }
    
    String subject=ePostaBilgisi.Konu;
    if(!subject?.trim()){
        subject=""
    }
    
    String content=ePostaBilgisi.Icerik;
    if(!content?.trim()){
        content=""
    }
    
    String mimeType=ePostaBilgisi.MesajTuru;
    if(!mimeType?.trim()){
        mimeType="text/html;charset=utf-8"
    }
    
    // Init constants of sender email account.
    String email = "info@apinizer.com"
    String password = "xxxx"
    String host = "mail.apinizer.com"
    String port = "587" //  "465" "587"
    
    // Set up properties.
    Properties props = System.getProperties()
    props.put("mail.smtp.user", email)
    props.put("mail.smtp.host", host)
    props.put("mail.smtp.port", port)
    props.put("mail.smtp.auth", "true")
    props.put("mail.smtp.starttls.enable","false")
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
    props.put("mail.smtp.ssl.trust", host) // Change host to "*" if you want to trust all host.
    
    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(email, password);
            }
        });
            
    // Set up message.
    MimeMessage message = new MimeMessage(session)
    message.setFrom(new InternetAddress(from))
    if(to?.trim()){
        String[] toStrArr=to.split(",");
        for (String m:toStrArr){
            message.addRecipients(Message.RecipientType.TO, InternetAddress.parse( m))
        }
    }
    if(cc?.trim()){
        String[] ccStrArr=cc.split(",");
        for (String m:ccStrArr){
            message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(m))
        }
    }
    if(bcc?.trim()){
        String[] bccStrArr=bcc.split(",");
        for (String m:bccStrArr){
            message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(m))
        }
    }
    message.setSubject(subject)
    message.setContent(content, mimeType)
    
    try {
        // Send mail.
        Transport.send(message )
    } catch (Exception e) {
        e.printStackTrace();
        statusCodeToTargetAPI=500;
        requestErrorMessageToTargetAPI = createSoapResponse(false,'Mail gönderirken hata oluştu:' + e.getMessage(),'01-ERR-05' );
        return;
    }
    statusCodeToTargetAPI=200;
    requestErrorMessageToTargetAPI = createSoapResponse(true,'' ,'' );
    
} catch (Exception e) {
    e.printStackTrace();
    statusCodeToTargetAPI=500;
    requestErrorMessageToTargetAPI = createSoapResponse(false,'Mail gönderirken hata oluştu:' + e.getMessage(),'01-ERR-06' );
    return;
}
GROOVY

Groovy Örnek 8: XML Parse edip JSON mesaj oluşturup REST API Call

import  tr.com.soagen.apinizer.util.*
 
  try{
    // clear table
    def get = new URL("http://192.168.100.100:30080/apigateway/personel/temizle").openConnection();
    get.setRequestMethod("GET")
    get.setDoOutput(true)
    get.setRequestProperty("Content-Type", "application/json")
    get.setRequestProperty("Username", "")
    get.setRequestProperty("Password", "")
    def getRC = get.getResponseCode();
    if(getRC.equals(400)|| getRC.equals(401)) {
        responseErrorMessageToClient="Yetkilendirme Hatası!";
    }
  }catch(Exception e){
 
  }
 
 
int itemCount = responseBodyTextToClient.count("<item>");
String templateJson = "{"+
"\"sicil_no\":\"#sicil_no\",    "+
"\"adi\"    :\"#adi\","+
"\"soyadi\" :\"#soyadi\","+
"\"isyeri_kodu\"    :\"#isyeri_kodu\","+
"\"calistigi_isyeri\"   :\"#calistigi_isyeri\","+
"\"ik_bilgileri\"   :\"#ik_bilgileri\","+
"\"calistigi_birim\"    :\"#calistigi_birim\","+
"\"unvani\" :\"#unvani\","+
"\"gorevi\" :\"gorevi\","+
"\"dogum_gunu\" :\"#dogum_gunu\","+
"\"ise_giris_tarihi\"   :\"#ise_giris_tarihi\","+
"\"yonetici_adi\"   :\"#yonetici_adi\","+
"\"yonetici_soyadi\"    :\"#yonetici_soyadi\","+
"\"yonetici_sicil\" :\"#yonetici_sicil\","+
"\"eposta\" :\"#eposta\","+
"\"telefon\"    :\"#telefon\","+
"\"tckimlikno\":\"#tckimlikno\""+
"}"
 
;
String hataliIdStr="";
for(int i=1; i < itemCount+1; i++){
   
    String valueJson = templateJson;
     
    String xpathId  = "(/ArrayList/item)["+i+"]/id"; 
    String valueId  = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpathId, true);
     
    try{
     
        String xpath  = "(/ArrayList/item)["+i+"]/secondaryNr"; 
        String value  = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#sicil_no" , value );
         
        xpath = "(/ArrayList/item)["+i+"]/name"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#adi" , value);
         
         
        xpath = "(/ArrayList/item)["+i+"]/surname"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#soyadi" , value);
         
         
        xpath = "(/ArrayList/item)["+i+"]/bizUnit/code"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#isyeri_kodu" , value);
         
         
        xpath = "(/ArrayList/item)["+i+"]/bizUnit/description"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#calistigi_isyeri" , value);
         
         
        xpath = "(/ArrayList/item)["+i+"]/orgUnit/code"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#ik_bilgileri" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/orgUnit/description"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#calistigi_birim" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/profession"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#unvani" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/jobTitle"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#gorevi" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/birthday"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        if(org.apache.commons.lang3.StringUtils.isNotBlank(value) && value.length()>10){
            value=value.substring(0,10);
        }
        valueJson = valueJson.replace("#dogum_gunu" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/entryDate"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        if(org.apache.commons.lang3.StringUtils.isNotBlank(value) && value.length()>10){
            value=value.substring(0,10);
        }
        valueJson = valueJson.replace("#ise_giris_tarihi" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/supervisor/name"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#yonetici_adi" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/supervisor/surname"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#yonetici_soyadi" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/supervisor/secondaryNr"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#yonetici_sicil" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/contactInfo/email"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#eposta" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/contactInfo/mobile1"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#telefon" , value);
         
        xpath = "(/ArrayList/item)["+i+"]/officialId"; 
        value = UtilXmlOperations.extractFromXmlBody( null, responseBodyTextFromTargetAPI,  xpath, true);
        valueJson = valueJson.replace("#tckimlikno" , value);
     
     
        // POST to DB
        def post = new URL("http://192.168.100.100:30080/apigateway/personel/kaydet").openConnection();
        post.setRequestMethod("POST")
        post.setDoOutput(true)
        post.setRequestProperty("Content-Type", "application/json")
        post.setRequestProperty("Username", "")
        post.setRequestProperty("Password", "")
        post.getOutputStream().write(valueJson.getBytes("UTF-8"));
        def postRC = post.getResponseCode();
 
        if(postRC.equals(400)|| postRC.equals(401)) {
            responseErrorMessageToClient="Yetkilendirme Hatası!";
            break;
        }
        if(!postRC.equals(200)) {
             hataliIdStr=valueId+","+hataliIdStr;
        }
    }catch(Exception e){
        hataliIdStr=valueId+","+hataliIdStr;
    }
  
} 
  
 
if(hataliIdStr.endsWith(",")){
    hataliIdStr = hataliIdStr.substring(0,hataliIdStr.length() - 1);
}
 
if(org.apache.commons.lang3.StringUtils.isNotBlank(hataliIdStr)){
    responseErrorMessageToClient=hataliIdStr+" id'li kayıtlar kaydedilemedi!";
}else{
    responseBodyTextToClient=
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"+
        "<soap:Body>"+
        "   <result>OK</result>"+
        "</soap:Body>"+
    "</soap:Envelope>";
}
GROOVY




JavaScript Örnek 1: Rest Api Call

var post = new org.apache.commons.httpclient.methods.PostMethod("https://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent("select item  from weather.forecast where woeid in  (select woeid from geo.places(1) where text='$location')"));
var client = new org.apache.commons.httpclient.HttpClient();

post.setRequestHeader("Content-type", "application/json"); 
post.setRequestHeader("Accept", "application/json");

var status = client.executeMethod(post);
var br = new java.io.BufferedReader(new java.io.InputStreamReader(post.getResponseBodyAsStream()));
var response = "";
var line = br.readLine();
while(line != null){
    response = response + line;
    line = br.readLine();
}
post.releaseConnection();

var item = JSON.parse(response);
requestHeaderMapFromClient.put("title" ,item.query.results.channel.item.title);
requestUrlParamMapFromClient.put("title" ,item.query.results.channel.item.title );
bodyText=  'title:'+ item.query.results.channel.item.title;
JS

  

JavaScript Örnek 2: Rest Api Call ile Apinizer'da tanımlı bir uç noktayı kullanmak

 var url = "http://10.1.1.1:30080/apigateway/apinizerlog/InsertLog";

 var tarih = new Date().toISOString();
 var servisAdi = 'Servis Adı Yazılacak';
 var uygulama = 'Uygulama Adı Yazılacak';
 var ip = headerMap.get('X-Forwarded-For');
 var kullaniciAdi = headerMap.get('username');
 var parametre = JSON.stringify(bodyText);
 
 var data = JSON.stringify({
   "Tarih": tarih,
   "ServisAdi": servisAdi,
   "IP": ip,
   "KullaniciAdi": kullaniciAdi,
   "Parametre": parametre,
   "Uygulama": uygulama

 });

 try {
   var con = new java.net.URL(url).openConnection();
   con.setConnectTimeout(15000);
   con.setReadTimeout(15000);
   con.setRequestMethod("PUT");
   con.setUseCaches (false);
   con.setDoInput(true);
   con.setDoOutput(true);
   con.setRequestProperty("Content-Length", data.length);
   
   var wr = new java.io.DataOutputStream(con.getOutputStream());
   wr.writeBytes(data);
   wr.flush();
   wr.close();
   con.getResponseCode();//onemli silinmemesi gerekli
 } catch (err) {
 }
JS