Forum Discussion

corki's avatar
corki
Contributor
15 years ago

HOW TO SEND REST or SOAP request by JAVA CODE

Hi all,

    I have already known how to SEND  SOAP request by using java (Eclipse).
    Now I need to know how to do the SAME but in REST service.


Here is example for sending SOAP request:

=========================================================================
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnFactory.createConnection();

MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
       
        SOAPPart soapPart      = message.getSOAPPart();
        StreamSource new_Request = new StreamSource( new ByteArrayInputStream(request.getBytes()) );
        soapPart.setContent( new_Request );
       
        message.saveChanges();
       
SOAPMessage reply = connection.call(message, endPoint);
// ..handle with reply
connection.close();
=========================================================================




    If someone can paste here similar EXAMPLE how to send request but by REST service.  Please, and Thank You All. !!!

4 Replies

  • import java.io.ByteArrayOutputStream;
    import java.io.InputStream;

    import java.net.HttpURLConnection;
    import java.net.URL;
    import com.eviware.soapui.impl.wsdl.*;
    import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
    import com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext;
    import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestStep;

    import com.eviware.soapui.impl.wsdl.teststeps.PropertyTransfer;
    import com.eviware.soapui.impl.wsdl.panels.support.MockTestRunContext;
    import com.eviware.soapui.impl.wsdl.panels.support.MockTestRunner;
    import com.eviware.soapui.model.testsuite.TestStepResult;

    public class FirstClass {

          // create new project

          static WsdlProject        project  = null;
        static WsdlTestSuite      testSuite = null;
        static WsdlTestCase      testCase  = null;
        static WsdlTestStep      testStep  = null;
        static WsdlTestRunContext context  = null;
        static String            endPoint  = null;
        static String            path  = null;
        static String            parameters = null;
        static String            requestURL = null;

       

       

        // M A I N

        public static void main(String[] args) {

               

                // SET PROXY
                //setProxySettings();

         

                // LOAD PROJECT DATA (project, suite, case, step)

                loadProject_step("C:/SVN_Repozitory/ncs/cds/flight stats/03.implementation/Flight-stats-soapui-project.xml",
                                            "Flights",  "FS_IATA2_flightNumber",  "FS_IATA2_flightNumber" );

               

                // SET UP REQUEST
                setUpRequestURL();
                                 

            // PREPARATION 1: Look for previous groovy scripts testSteps, to run them first (should set the data first)
                //runStartUpScripts();


            // execute OUR special testStep
                executeProject_step();             

          } 

       

       

        // F U N C T I O N S:

           

          public static void loadProject_step(String projectPath, String testSuiteName, String testCaseName, String testStepName) {

               

                // create new project

                project  = new WsdlProject( projectPath, "" );

                           

              testSuite = project.getTestSuiteByName(testSuiteName);
              testCase  = testSuite.getTestCaseByName(testCaseName);
              testStep  = testCase.getTestStepByName(testStepName);
              context  = new WsdlTestRunContext( testStep );
              endPoint  = expandProperties(context, testStep.getPropertyValue("endpoint"));
              path  = expandProperties(context, testStep.getPropertyValue("path"));
          }

          public static void setUpRequestURL() {

            System.out.println("\n==================================");

             

              parameters = "?";
              for(int i=0; i< testStep.getPropertyCount(); i++ ) {         
                if( testStep.getPropertyAt(i).getValue() != null && testStep.getPropertyAt(i).getValue().compareTo("") != 0

                            &&testStep.getPropertyAt(i).getName().compareTo("Endpoint")!=0
                            && testStep.getPropertyAt(i).getName().compareTo("Domain")!=0
                            && testStep.getPropertyAt(i).getName().compareTo("ResponseAsXml")!=0
                            && testStep.getPropertyAt(i).getName().compareTo("Password")!=0
                            && testStep.getPropertyAt(i).getName().compareTo("Path")!=0
                            && testStep.getPropertyAt(i).getName().compareTo("Username")!=0
                            && testStep.getPropertyAt(i).getName().compareTo("Response")!=0) {

                     

                      System.out.println(testStep.getPropertyAt(i).getName() + " = " + expandProperties(context, testStep.getPropertyAt(i).getValue()) );

                      if(parameters.length()<2) parameters = parameters +      testStep.getPropertyAt(i).getName() + "=" + expandProperties(context, testStep.getPropertyAt(i).getValue());

                      else                      parameters = parameters + "&" + testStep.getPropertyAt(i).getName() + "=" + expandProperties(context, testStep.getPropertyAt(i).getValue());

                }//if

              }//for

              System.out.println("==================================");
              requestURL = endPoint + path + parameters;
              System.out.println("requestURL : " + requestURL);     
          }
         

          public static String expandProperties(WsdlTestRunContext context, String request) {
                // use everything what found in ( ... )  ---->  context.expand( ... )

                int index = request.indexOf("${");
                while(index >= 0) {

                      int endIndex = request.indexOf("}") + 1;
                      String foundString = request.substring(index, endIndex);
                      String toReplaceString = context.expand( foundString ); // extract VALUE using SoapUI method expand.

                      request = request.replaceFirst("(\\$\\{.+\\})", toReplaceString);
                      index = request.indexOf("${");

                }
                return request;
          }

         

          public static void setProxySettings() {

                // PROXY SETTINGS

                System.getProperties().put("http.proxyHost", "172.168.30.36"); 
                System.getProperties().put("http.proxyPort", "8080"); 

                //System.getProperties().put("http.proxyUser", "someUserName"); 
                //System.getProperties().put("http.proxyPassword", "somePassword");
          }   

         

          public static void runStartUpScripts() {

                try {

                  System.out.print("\nRuning Project's Load script ...");
                  if( project.getAfterLoadScript()!=null && project.getAfterLoadScript().replaceAll(" ", "").length() > 2 ) {
                      project.runAfterLoadScript();
                      System.out.print("DONE");

                  }

                  else System.out.print("empty");         
               

                  System.out.print("\nRuning Project's Save script ...");
                  if( project.getBeforeSaveScript()!=null && project.getBeforeSaveScript().replaceAll(" ", "").length() > 2 ) {
                      project.runBeforeSaveScript();
                      System.out.println("DONE");

                  }

                  else System.out.println("empty");       

                 

                  System.out.print("\nRuning TestSuite's Setup script ...");
                  if( testSuite.getSetupScript()!=null &&  testSuite.getSetupScript().replaceAll(" ", "").length() > 2 ) {
                      testSuite.runSetupScript(context);
                      System.out.print("DONE");

                  }

                  else System.out.print("empty");

                 

                  System.out.print("\nRuning TestSuite's TearDown script ...");
                  if( testSuite.getTearDownScript()!=null && testSuite.getTearDownScript().replaceAll(" ", "").length() > 2 ) {
                      testSuite.runTearDownScript(context);
                      System.out.println("DONE");

                  }

                  else System.out.println("empty");       

                 

                  System.out.print("\nRuning TestCases's Setup script ...");
                  if( testCase.getSetupScript()!=null && testCase.getSetupScript().replaceAll(" ", "").length() > 2 ) {
                      testCase.runSetupScript(context , context.getTestRunner());
                      System.out.print("DONE");

                  }

                  else System.out.print("empty");

                 

                  System.out.print("\nRuning TestCases's TearDown script ...");

                  if( testCase.getTearDownScript()!=null && testCase.getTearDownScript().replaceAll(" ", "").length() > 2 ) {

                      testCase.runTearDownScript(context , context.getTestRunner());
                      System.out.println("DONE");

                  }

                  else System.out.println("empty");

                } catch(Exception e) {

                    System.out.println(e.getMessage());

                }         

          }// runStarUpScripts() 

         

          public static void runSpecialTestStepsFirst() {

               

            // Check for special steps to run them first if needed

            TestStepResult ts_result = null;

            if( testCase.getIndexOfTestStep(testStep) > 0) {

                boolean transfer_found = false;
                for(int i=0; i                  if(testCase.getTestStepAt(i).getModelItem().toString().indexOf("PropertyTransfersTestStep") >= 0 ) {
                            transfer_found = true;
                            System.out.println("\nFound a Transfer Property - step as first.");
                            PropertyTransfer my = new PropertyTransfer(testCase.getTestStepAt(i));
                            System.out.println(testCase.getTestStepAt(i).getName());
                            System.out.println("--------- SOURCE---------->> " + my.getSourceStepName());
                            System.out.println("--------- TARGET---------->> " + my.getTargetStepName());
                      }
                }

                for(int i=0; i
                      if(testCase.getTestStepAt(i).getModelItem().toString().indexOf("WsdlGroovyScriptTestStep") >= 0 || transfer_found == true) {

                            // run this groovy script

                            MockTestRunner mockTR = new MockTestRunner(testCase);
                            MockTestRunContext mockTRContext = new MockTestRunContext(mockTR, testStep);
                            System.out.println("\nRunning ... ------------ >>> " + testCase.getTestStepAt(i).getName());

                            ts_result = testCase.getTestStepAt(i).run(mockTR, mockTRContext);

                      }               
                }
            }       

          }// runSpecialTestStepsFirst()     

         

          public static void executeProject_step() {

                try {

                      URL targetURL = new URL(requestURL);

                      HttpURLConnection conn = (HttpURLConnection) targetURL.openConnection();
                      conn.setAllowUserInteraction(true);
                      conn.setConnectTimeout(15000); // 15 sec. connection timeout
                      conn.setDoInput(true);
                      conn.setDoOutput(true);
                      conn.setUseCaches(false);
                      conn.setRequestMethod("GET");
                      conn.setRequestProperty("Content-type", "text/html; charset=" + "UTF-8");

                      long timeTaken = System.currentTimeMillis();
                      conn.connect(); // just sending the request.
                      timeTaken = System.currentTimeMillis() - timeTaken;
                      System.out.println("The response >>> " + conn.getResponseMessage() + " , timeTaken: " + timeTaken + " ms");
                      System.out.println("\n  RESPONSE :");


                     

                      String str;

                      InputStream inputstream = null;



                  inputstream = conn.getInputStream();

                  int length = (int) conn.getContentLength();

                  if (length != -1)

                  {

                      byte incomingData[] = new byte[length];

                      inputstream.read(incomingData);

                      str = new String(incomingData);

                  }

                  else {

                      ByteArrayOutputStream bytestream = new ByteArrayOutputStream();

                      int ch = 0;

                      while ((ch = inputstream.read()) != -1) {

                            bytestream.write(ch);

                      }

                      str = new String(bytestream.toByteArray());
                      bytestream.close();

                  }

                  System.out.println(str);           

                  conn.disconnect(); // we don't like to wait for response

                }

                catch (Exception e) {

                }

          }// executeProject_step()   

    }
    • dan11223's avatar
      dan11223
      New Contributor

      Hallo corki

      Where can I download com.eviware.soapui.jar to use with your code above ?

       

      • dan11223's avatar
        dan11223
        New Contributor

        Or can you please post the whole connection code of SOAP Solution, please ?

         

        HOW TO SEND SOAP request by JAVA CODE