Thursday, January 20, 2011

Java And SSL Steps to configure Java HTTP Client to use SSL website Example

Java And SSL Steps to configure Java Client to use SSL website Example

Getting Execption  : javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Are you getting this error? This simply means that the web server or the URL you are connecting to does not have a valid certificate from an authorized CA. But however, being a programmer you would want to find out the alternative way to solve this issue.
What you need to do is to import the server certificate and install it in your JDK's keystore. If I am talking greek, its ok. I too just leant this. Just follow these steps and you will be able to get rid of that error.


Follow the below steps to access the ssl URL via Java
1. First of all you copy the URL that you are connecting to and paste it in your browser. Let us say you are using IE. Just paste the url in the address bar and press enter.
2. You will now probably see a dialog box warning you about the certificate. Now click on the 'View Certificate' and install the certificate. Ignore any warning messages.
3. Now that the server certificate is installed in your computer, your browser will not warn you when you visit the same site again. But however your JRE dumb as it is does not yet know about this certificate's existence until you add it to its keystore. Usually you will use the keytool to manage certificates. Keytool is a command-line utility with numerous arguments that allow you to create and manage keystores for housing digital certificates. For the complete documentation of keytool,http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html
4. You can list the current certificates contained within a keystore using they keytool -list command. The initial password for the cacerts keystore is changeit. For example:
    C:\Program Files\Citrix\Citrix Extranet Server\SGJC\jre\bin>keytool -list-keystore ..\lib\security\cacerts
    Enter keystore password: changeit
    You will then see the something like this:
    Keystore type: jks
    Keystore provider: SUN
    Your keystore contains 11 entries:
    engweb, Wed Apr 11 16:22:49 EDT 2001, trustedCertEntry,
    Certificate fingerprint (MD5): 8C:24:DA:52:7A:4A:16:4B:8E:FB:67:44:C9:D2:E4:16
    thawtepersonalfreemailca, Fri Feb 12 15:12:16 EST 1999, trustedCertEntry,
    Certificate fingerprint (MD5): 1E:74:C3:86:3C:0C:35:C5:3E:C2:7F:EF:3C:AA:3C:D9
    thawtepersonalbasicca, Fri Feb 12 15:11:01 EST 1999, trustedCertEntry,
    Certificate fingerprint (MD5): E6:0B:D2:C9:CA:2D:88:DB:1A:71:0E:4B:78:EB:02:41
    verisignclass3ca, Mon Jun 29 13:05:51 EDT 1998, trustedCertEntry,
    Certificate fingerprint (MD5): 78:2A:02:DF:DB:2E:14:D5:A7:5F:0A:DF:B6:8E:9C:5D
    thawteserverca, Fri Feb 12 15:14:33 EST 1999, trustedCertEntry,
    Certificate fingerprint (MD5): C5:70:C4:A2:ED:53:78:0C:C8:10:53:81:64:CB:D0:1D
    thawtepersonalpremiumca, Fri Feb 12 15:13:21 EST 1999, trustedCertEntry,
    Certificate fingerprint (MD5): 3A:B2:DE:22:9A:20:93:49:F9:ED:C8:D2:8A:E7:68:0D
      verisignclass4ca, Mon Jun 29 13:06:57 EDT 1998, trustedCertEntry,
      Certificate fingerprint (MD5): 1B:D1:AD:17:8B:7F:22:13:24:F5:26:E2:5D:4E:B9:10
      verisignclass1ca, Mon Jun 29 13:06:17 EDT 1998, trustedCertEntry,
      Certificate fingerprint (MD5): 51:86:E8:1F:BC:B1:C3:71:B5:18:10:DB:5F:DC:F6:20
    verisignserverca, Mon Jun 29 13:07:34 EDT 1998, trustedCertEntry,
    Certificate fingerprint (MD5): 74:7B:82:03:43:F0:00:9E:6B:B3:EC:47:BF:85:A5:93
    thawtepremiumserverca, Fri Feb 12 15:15:26 EST 1999, trustedCertEntry,
    Certificate fingerprint (MD5): 06:9F:69:79:16:66:90:02:1B:8C:8C:A2:C3:07:6F:3A
    verisignclass2ca, Mon Jun 29 13:06:39 EDT 1998, trustedCertEntry,
    Certificate fingerprint (MD5): EC:40:7D:2B:76:52:67:05:2C:EA:F2:3A:4F:65:F0:D8
5. Now you have to add the previosly installed certificate to this keystore. To add, begin by exporting your CA Root certificate as a DER-encoded binary file and save it as C:\root.cer. (you can view the installed certificates under Tools->'Internet Options' ->Content->Certificates. Once you open the certificates, locate the one you just installed under 'Trusted Root Certification Authorities". Select the right one and click on 'export'. You can now save it (DER encoded binary) under your c: drive.
6. Then use the keytool -import command to import the file into your cacerts keystore. 
    For example:-alias myprivateroot -keystore ..\lib\security\cacerts -file c:\root.cer
Enter keystore password: changeit
Owner: CN=Division name, OU=Department, O=Your Company, L=Anytown,
ST=NC, C=US, EmailAddress=you@company.com
Issuer: CN=Division name, OU=Department, O=Your Company, L=Anytown,
ST=NC, C=US, EmailAddress=you@company.com
Serial number: 79805d77eecfadb147e84f8cc2a22106
Valid from: Wed Sep 19 14:15:10 EDT 2001 until: Mon Sep 19 14:23:20 EDT 2101
Certificate fingerprints:
MD5: B6:30:03:DC:6D:73:57:9B:F4:EE:13:16:C7:68:85:09
SHA1: B5:C3:BB:CA:34:DF:54:85:2A:E9:B2:05:E0:F7:84:1E:6E:E3:E7:68
Trust this certificate? [no]: yes
Certificate was added to keystore
7. Now run keytool -list again to verify that your private root certificate was added:
    C:\Program Files\Citrix\Citrix Extranet Server\SGJC\jre\bin>keytool -list -keystore ..\lib\security\cacerts
You will now see a list of all the certificates including the one you just added.
This confirms that your private root certificate has been added to the Extranet server cacerts keystore as a trusted certificate authority.

Some tips: Make sure that the certificate is in java keystore...in ubuntu 
do from terminal do > whereis java
then go to that location and ..\lib\security\carcerts and add the certificate using the above process.


I will surely resolve many defects.

Java Class Example
package com.tibco;

import java.io.*;
import java.net.*;
import java.sql.Timestamp;
import java.util.Calendar;

import javax.net.ssl.*;

class MyVerified implements HostnameVerifier {
       public boolean verify(String hostname, SSLSession session) {
           return true;
       }
    }


public class TibcoConnection {
   public static void main(String[] argv) throws Exception {
       StringBuffer contents= new StringBuffer();
        try{
            FileInputStream fstream = new FileInputStream("/home/localadmin/test.xml");
          
            DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
           
            while ((strLine = br.readLine()) != null)   {
             contents.append(strLine);
            }
            in.close();
          
            }catch (Exception e){
              System.err.println("Error: " + e.getMessage());
            }
   
   
      URL url = new URL("https://xyz/");
      HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
      connection.setDoOutput(true);
      connection.setDoInput(true);
     
      Calendar calendar = Calendar.getInstance();
      Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
      String        timeStamp                = currentTimestamp.toString();
      System.out.println(timeStamp);
        System.out.println(timeStamp);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3" );
        connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        connection.setRequestProperty("Accept-Language","en-us,en;q=0.5");
        connection.setRequestProperty("Accept-Encoding","gzip,deflate");
        connection.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
        connection.setRequestProperty("Keep-Alive","115");
        connection.setRequestProperty("Connection","keep-alive");
        connection.setRequestProperty("Channel", "DOC");
      connection.setHostnameVerifier(new MyVerified());
      connection.setDoOutput(true);
      BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
         System.out.println(line);
      }
      in.close();
   }

Another Java Class example 

package com.tibco;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import ch.qos.logback.classic.Logger;

public class WcfWrapper{
   
    public static void callWcf() throws Exception {
        InputStream responsexml=null;
        DefaultHttpClient httpclient = new DefaultHttpClient();
        System.setProperty("javax.net.ssl.keyStore","/usr/local/glassfish-3.0.1/glassfish/domains/domain1/config/client_keystore.jks");
        System.setProperty("javax.net.ssl.keyStorePassword","changeit");
        System.setProperty("javax.net.ssl.trustStorePassword","changeit");
        System.setProperty("javax.net.ssl.trustStore","/usr/local/glassfish-3.0.1/glassfish/domains/domain1/config/client_cacerts.jks");
        System.setProperty("javax.net.debug","all");
       
     
      
           java.net.URI uri = URIUtils.createURI("https", "localhost", 8443, "",
                 null,
                  null);
        HttpPost httpost = new HttpPost(uri);
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("rawXML", "asc"));
        httpclient.getParams().setParameter("http.socket.timeout", new
                Integer(55000));
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        System.out.println("Test");
        HttpResponse response = httpclient.execute(httpost);
        BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
        System.out.println("Post Form " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
        System.out.println(entity.getContentType());
     try{
         responsexml = entity.getContent();
        if(response!=null){
            System.out.println(entity.getContentLength());
        }
        byte[] fileBArrayrawxml = new byte[(int)entity.getContentLength()];
        responsexml.read(fileBArrayrawxml,0,(int)entity.getContentLength());
        System.out.println("hi"+new String(fileBArrayrawxml));
        responsexml.close();
      }catch(Exception e){
          e.printStackTrace();
         
      }finally{
          responsexml.close();
      }
    }


public static void main(String args[]){
//    WcfWrapper a = new WcfWrapper();
    try{
        WcfWrapper.callWcf();}catch(Exception e){}
}
}

Restful webservice with SSL

On Glassfish server create a Restful Hello Webservice- this service is avaliable from the samples - Install Glassfish 6.9 then from plugins install Restful. In it you will get restful webservice.

Test the Webservice http://localhost:4848 and in go to Network listeners enable 8443 port and put the certificate alias and keystore which was generated in the previous step using keytool...if dont know google for generating the certificate.


Go to netbeans again open web.xml go to security and click on add constraint.

Put in the url which you go from testwebservice webpage it would be something linke this http://localhost:8080/HelloWorld/resources/helloworld


Now put in this url in security contraint and change it to https://localhost:8443.....
Now right click on the project go to properties and run and remove resources/helloworld

Now go to source and open the helloworld.java you will find Path("/helloworld")
remove helloworld

Now your webservice is https://localhost:8443 and we have removed all the traling spaces..








Create a SSL key value for Mutual Authentication

In order to be able to use mutual authentication, we need to do the following:
    • Create a client keystore.
    • Export the client certificate from the client keystore.
    • Import the client certificate to the server truststore.
    • Create a client truststore.
    • Export the server certificate from the server keystore.
    • Import the server certificate to the client truststore.
The examples in this section will use the GlassFish application server in its default configuration.
The GlassFish installation directory will be referred to as GLASSFISH_DIR. We also need to work
from some terminal window, since we need to use the keytool command to create and manipulate
key and truststores.
    •  Create a directory named “client” at some arbitrary location.
    •  Create a directory named “server” inside the “client” directory created in the previous step.
    •  Back up the cacerts.jks file located in the GLASSFISH_DIR/domains/domain1/config/
       directory.
    •  Copy the cacerts.jks file that you just backed up to the “server” directory.
    •  Back up the keystore.jks file located in the GLASSFISH_DIR/domains/domain1/config/
       directory.
    •  Copy the keystore.jks file that you just backed up to the “server” directory.
    •  Open a terminal window and go to the “client” directory.
    •  Using the keytool command, create the client keystore and key as follows. The questions
       ansked by the keytool program can be answered more or less arbitrarily, as long as you
       remember the alias of the key you generate.
 keytool -genkey -alias client -keypass changeit -storepass changeit -keystore
 client_keystore.jks
 What is your first and last name?
   [Unknown]: My Client
 What is the name of your organizational unit?
   [Unknown]: Client Org Unit
 What is the name of your organization?
   [Unknown]: Client Org
 What is the name of your City or Locality?
   [Unknown]: Client City
 What is the name of your State or Province?
   [Unknown]: Client State
 What is the two-letter country code for this unit?
   [Unknown]: US
                                                  235
Is CN=My Client, OU=Client Org Unit, O=Client Org, L=Client City, ST=Client State, C=US
correct?
  [no]: yes
   •  Using the keytool command, export the client certificate.
keytool -export -alias client -keystore client_keystore.jks -storepass changeit -file
client.cer
Certificate stored in file <client.cer>
   •  Import the client certificate to the server truststore.
keytool -import -v -trustcacerts -alias client -keystore server/cacerts.jks -keypass
changeit -file client.cer
Enter keystore password: changeit
Owner: CN=My Client, OU=Client Org Unit, O=Client Org, L=Client City, ST=Client State,
C=US
Issuer: CN=My Client, OU=Client Org Unit, O=Client Org, L=Client City, ST=Client State,
C=US
Serial number: 49cadb4c
Valid from: Thu Mar 26 19:33:00 CST 2009 until: Wed Jun 24 19:33:00 CST 2009
Certificate fingerprints:
       MD5: 00:E7:89:7B:FA:2D:65:21:CC:65:A8:AA:FF:FC:F7:2F
       SHA1: 23:9F:2D:E1:6B:27:ED:CA:A3:83:90:47:9C:CF:55:C7:59:A6:14:2C
Trust this certificate? [no]: yes
Certificate was added to keystore
[Storing server/cacerts.jks]
   •  Change directory to the “server” directory.
   •  Export the server certificate.
keytool -export -alias s1as -keystore keystore.jks -storepass changeit -file server.cer
Certificate stored in file <server.cer>
   •  Go back to the “client” directory.
   •  In one single step, create the client truststore and import the server certificate into it.
keytool -import -v -trustcacerts -alias s1as -keystore client_cacerts.jks -storepass
changeit -keypass changeit -file server/server.cer
Owner: CN=Bo5b.local, OU=Sun Java System Application Server, O=Sun Microsystems, L=Santa
Clara, ST=California, C=US
Issuer: CN=Bo5b.local, OU=Sun Java System Application Server, O=Sun Microsystems,
L=Santa Clara, ST=California, C=US
Serial number: 47e86844
Valid from: Tue Mar 25 19:49:40 CST 2008 until: Fri Mar 23 19:49:40 CST 2018
Certificate fingerprints:
       MD5: 9A:70:E1:43:87:71:6B:A1:52:E0:B7:55:93:B6:DA:74
       SHA1: D8:04:53:C4:46:88:8B:30:EA:DC:1C:1C:1A:90:2B:ED:49:5C:9F:27
Trust this certificate? [no]: yes
Certificate was added to keystore
[Storing client_cacerts.jks]
   •  Copy the files cacerts.jks and keystore.jks from the “server” directory to the
      GLASSFISH_DIR/domains/domain1/config/ directory, replacing any files with the same
      names.
   •  If GlassFish is running, restart it, so that the modified keystore and truststore takes effect.
   •  Save the client_cacerts.jks and client_keystore.jks files – the web service clients in the
      examples below will need these files.
                                                   236
Web Tier Web Services
In this section we will implement a servlet-based web service and associated client and then show
how to apply access control, SSL and mutual authentication to this web service and its client.
Servlet Based Web Service
First we will implement the basic servlet-based web service without any encryption:
     •     Create a dynamic web project in Eclipse that uses the GlassFish server.
           I have called my project JAX-WS_GreetingServletMutualAuth.
     •     Implement the web service as follows:
 package com.ivan;
 import java.util.Date;
 import javax.jws.WebService;
 /**
   * This class implements the JAX-WS Hello World web service.
   * This is the servlet version of the web service.
   *
   * @author Ivan A Krizsan
   */
 @WebService
 public class HelloWorldWS
 {
       /* Constant(s): */
       /* Instance variable(s): */
       @Resource
       private WebServiceContext mWSContext;
       /**
         * Greets the user by composing a greeting-string including supplied
         * message.
         *
         * @param inMessage Message to be included in greeting string.
         * @return Greeting string.
         */
       public String hello(final String inMessage)
       {
              return "Hello from Servlet WS: " + inMessage + " " +
                  new Date() + ", the principal is: " +
                  mWSContext.getUserPrincipal();
       }
 }
     •     If not already present, create a web.xml file in the WEB-INF directory with the following
           contents.
 <?xml version="1.0" encoding="UTF-8"?>
 <web-app
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       xsi:schemaLocation="
              http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
              id="WebApp_ID" version="2.5">
       <display-name>JAX-WS_GreetingServletMutualAuth</display-name>
 </web-app>
                                                     237
     •   If not already present, create a sun-web.xml file in the WEB-INF directory with the
         following contents.
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0
 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
 <sun-web-app error-url="">
       <context-root>/JAX-WS_GreetingServletMutualAuth</context-root>
       <!-- The stuff below is just default settings. -->
       <class-loader delegate="true" />
       <jsp-config>
            <property name="keepgenerated" value="true"/>
       </jsp-config>
 </sun-web-app>
     •   Start GlassFish.
     •   Deploy the web service to GlassFish.
Web Service Client
The web service client used in this example is a standalone Java program that only relies on the
Java 6 runtime environment. To set up an Eclipse project for the client:
     •   Create a Java project.
     •   Copy the client keystore and truststore files, client_cacerts.jks and client_truststore.jks, into
         the root of the project.
     •   Implement the main client class:
         Note that there will be errors in this class until we have generated additional classes needed
         on the client side in the next step.
 package com.ivan.client;
 import   javax.net.ssl.HostnameVerifier;
 import   javax.net.ssl.HttpsURLConnection;
 import   javax.net.ssl.SSLSession;
 import   com.ivan.HelloWorldWS;
 import   com.ivan.HelloWorldWSService;
 /**
   * Standalone static JAX-WS client invoking the secured Hello service.
   * When launching the program, the following VM flags need to be set
   * for SSL:
   * -Djavax.net.ssl.trustStore=client_cacerts.jks
   * -Djavax.net.ssl.trustStorePassword=changeit
   *
   * Additionally, for mutual authentication:
   * -Djavax.net.ssl.keyStore=client_keystore.jks
   * -Djavax.net.ssl.keyStorePassword=changeit
   *
   * Finally, when debugging SSL handshakes etc:
   * -Djavax.net.debug=all
   *
   * @author Ivan A Krizsan
   */
 public class HelloWSClient
 {
       static
       {
            /*
             * Java by default verifies that the certificate CN (Common Name) is
                                                     238
        * the same as host name in the URL. If the CN in the certificate is
        * not the same as the host name, your web service client fails.
        * This piece of code allows for using localhost as host name
        * with a certificate in which the CN does not match.
        * This is meant to be a workaround while developing the web
        * service and clients and SHOULD be removed in the production
        * version.
        */
      HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
      {
           public boolean verify(String hostname, SSLSession session)
           {
               if (hostname.equals("localhost"))
               {
                   return true;
               }
               return false;
           }
      });
  }
  /* Instance variable(s): */
  private HelloWorldWSService mHelloWorldService;
  public static void main(String[] args)
  {
      HelloWSClient theClient = new HelloWSClient();
      theClient.callService();
  }
  private void callService()
  {
      mHelloWorldService = new HelloWorldWSService();
      System.out.println("Service object: " + mHelloWorldService);
      HelloWorldWS thePort = mHelloWorldService.getHelloWorldWSPort();
      String theResponse = thePort.hello("Steven Segal");
      System.out.println("Response from web service: " + theResponse);
  }
}

Php Curl SSL


 check php.info if openssl is installed if there is a version confict it can affect connection 

http://www.php.net/manual/en/function.curl-setopt.php

<?php
require_once 'TibcoConnector.php';
//function sendEncodedImage($image,$claimNumber){
$xmlToSend ="<Pro>.....</Pro>";

try {
    $output = new TibcoConnector();
    $responseData=$output->passXmlToTibco($xmlToSend);
    $parsedOutput=parseResponseData($responseData);
    //    echo $parsedOutput;
    if (strlen($responseData)) {
        //        echo $responseData;
    } else {
        //    echo "Service is Down- Please try again later";
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
//}

function getRandomNumber(){
    srand(time());
    $random = (rand()%100);
    return $random;
}

function getCurrentTime(){
    $time_now=mktime(date('h'),date('i'),date('s'));
    $currentTime= date('h.i.s',$time_now);
    return $currentTime;
}

function parseResponseData($responseData){
    $targetstring = "No Document ID Generated";
    $targetstring1 = "An item already exists for";
    $targetstring2 = "Error";
    $targetstring3 = "SCANNER";
    if(stristr($responseData, $targetstring) === TRUE) {
        return "No Document ID";
    }
    elseif(stristr($responseData, $targetstring1) === TRUE){
        return "This case number is already present";
    }
    elseif(stristr($responseData, $targetstring2) === TRUE){
        return "Error";
    }
    elseif(stristr($responseData, $targetstring3) === TRUE){
        $start=strpos($responseData,$targetstring3);
        $end=strpos($responseData,"Application");
        $inbetweenString = substr($responseData,$start,$start-$end);
        return "Error";
    }
    else{
    //    echo $responseData;
        $modifiedData = str_replace("ns0:", "", $responseData);
        $xml = simplexml_load_string($modifiedData);
        foreach($xml->children()->children()->children() as $child)
        {
            if ($child->getName() ==="CaseNumber"){
                $caseNumber=$child;
            }
        }
        echo $caseNumber;
    }
}
?>


TibcoConnector.php

<?php
require_once 'RemoteConnector.php';
class TibcoConnector{
protected $_error;
protected $_flag=true;
protected $_count=0;
    public function passXmlToTibco($theData){
    //    $url = 'https://......';
        try {
            $output = new Pos_RemoteConnector($url,$theData);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        return $output;
   
}
}


<?php
class Pos_RemoteConnector
{
    protected $_url;
    protected $_remoteFile;
    protected $_error;
    protected $_urlParts;
    protected $_status;
    public    $_flag=true;
    public function __construct($url,$contents)
    {
        $this->_url = $url;
        $this->_contents='xml='.$contents;
        //    $this->checkURL();
        if (function_exists('curl_init')) {
            $this->useCurl();
        } else {
            echo "Site is down-Please be patience";
        }
    }

    protected function checkURL()
    {
        $flags = FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED;
        $urlOK = filter_var($this->_url, FILTER_VALIDATE_URL, $flags);
        $this->_urlParts = parse_url($this->_url);
        if (!$urlOK || $this->_urlParts['scheme'] != 'http') {
            throw new Exception($this->_url . ' is not a valid URL');
        }
        $domainOK = preg_match('/^[^.]+?\.\w{2}/', $this->_urlParts['host']);
        if (!$urlOK) {
            throw new Exception($this->_url . ' is not a valid URL');
        }
    }

    protected function useCurl()
    {

        if ($session = curl_init($this->_url)) {
            curl_setopt($session, CURLOPT_HTTPHEADER,array('Servi:C'));
            curl_setopt($session, CURLOPT_HEADER, 0);
            curl_setopt($session, CURLOPT_POST, 1);
            curl_setopt($session, CURLOPT_POSTFIELDS,$this->_contents);
            curl_setopt($session, CURLOPT_PORT, portnumber integer); //Set the port number
            curl_setopt($session, CURLOPT_TIMEOUT, 1500); // times out after 15s
            curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($session, CURLOPT_SSLVERSION,3);
            curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($session, CURLOPT_VERBOSE, '1');
//            curl_setopt($session, CURLOPT_SSL_VERIFYPEER, true);
//            curl_setopt($session, CURLOPT_SSL_VERIFYHOST, 0);
//            curl_setopt($session, CURLOPT_CAINFO, "/etc/ssl/certs/");
            $this->_remoteFile = curl_exec($session);
            $this->_status = curl_getinfo($session, CURLINFO_HTTP_CODE);
            if(curl_errno($session))
            {
                echo 'error:' . curl_error($session);
            }
               
            curl_close($session);
        } else {
            $this->_error = 'Cannot establish cURL session';
        }
    }
    public function __toString()
    {
            $returnString=$this->_remoteFile;
     if(isset($returnString)&&!empty($returnString)){
         //echo $this->_remoteFile;
         return $this->_remoteFile;
     }
     else{
     //    var_dump($this->_remoteFile);
     //    echo $this->_remoteFile;
         //return "Tibco Call failed-Try one more time";
     }
    }

    public function getErrorMessage()
    {
        if (is_null($this->_error)) {
            $this->setErrorMessage();
        }
        return $this->_error;
    }

    protected function removeHeaders()
    {
        $parts = preg_split('#\r\n\r\n|\n\n#', $this->_remoteFile);
        if (is_array($parts)) {
            $headers = array_shift($parts);
            $file = implode("\n\n", $parts);
            if (preg_match('#HTTP/1\.\d\s+(\d{3})#', $headers, $m)) {
                $this->_status = $m[1];
            }
            if (preg_match('#Content-Type:([^\r\n]+)#i', $headers, $m)) {
                if (stripos($m[1], 'xml') !== false || stripos($m[1], 'html') !== false) {
                    if (preg_match('/<.+>/s', $file, $m)) {
                        $this->_remoteFile = $m[0];
                    } else {
                        $this->_remoteFile = trim($file);
                    }
                } else {
                    $this->_remoteFile = trim($file);
                }
            }
        }
    }

    protected function setErrorMessage()
    {
        if ($this->_status == 200 && $this->_remoteFile) {
            $this->_error = '';
        } else {
            switch ($this->_status) {
                case 200:
                case 204:
                    $this->_error = 'Connection OK, but file is empty.';
                    break;
                case 301:
                case 302:
                case 303:
                case 307:
                case 410:
                    $this->_error = 'File has been moved or does not exist.';
                    break;
                case 305:
                    $this->_error = 'File must be accessed through a proxy.';
                    break;
                case 400:
                    $this->_error = 'Malformed request.';
                    break;
                case 401:
                case 403:
                    $this->_error = 'You are not authorized to access this page.';
                    break;
                case 404:
                    $this->_error = 'File not found.';
                    break;
                case 407:
                    $this->_error = 'Proxy requires authentication.';
                    break;
                case 408:
                    $this->_error = 'Request timed out.';
                    break;
                case 500:
                    $this->_error = 'The remote server encountered an internal error.';
                    break;
                case 503:
                    $this->_error = 'The server cannot handle the request at the moment.';
                    break;
                default:
                    $this->_error = 'Undefined error. Check URL and domain name.';
                    break;
            }
        }
    }
}