0

I need to achieve HTTP connection pooling using multithread environment. I am using below mentioned code. The mentioned serviceURL takes approx 1-3 sec to respond, however i am getting approx 30-50 hits per/second from client. I need to hit single URL with different properties. So i am not clear, what should i do to respond the all hits(30-40 hits/sec). If HttpURLConnection already does connection pooling then is multithreading is the solution for it.

I tried to convert this program using HTTPClient but unfortunately it is not working properly. So can you tell me how can i convert this code to HTTPClient using multi-threaded environment.

package airtel.product.action;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.apache.commons.codec.binary.Base64;

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;


public class HTTPSClient {
    public static void main(String[] args) {
        try {
            doHttpsPost("9711296535", "0.5", "0.5");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    private static HttpsURLConnection getHTTPSConnection(String url) throws Exception{
        URL chargingUrl;

        HostnameVerifier hv = new HostnameVerifier(){
        public boolean verify(String urlHostName, SSLSession session) {
        System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost());
        return true;
        }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv); 
        KeyStore ks;
        HttpsURLConnection urlc=null;
        //try {
            chargingUrl = new URL(url);
            ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream("/vishnu/twss/keystore/KEYSTORE.jks"), "12345678".toCharArray());//Location of keystore c:\\SDPKeystore.dat,12345678
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, "airtel@123".toCharArray()); //password is airtel@123
            TrustManager[] tm;
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ks);
            tm = tmf.getTrustManagers();
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(kmf.getKeyManagers(), tm, null);
            SSLSocketFactory sslSocketFactory =sslContext.getSocketFactory();
            urlc = (HttpsURLConnection) chargingUrl.openConnection();
            urlc.setSSLSocketFactory(sslSocketFactory); 
            //System.out.println("DoHttpPost(): Connection received");
            //System.out.println("DoHttpPost(): Setting UserName and Password");                        
            String usernamePassword = "vishnu" + ":" + "air@123";
            String encoding = null;

            byte[] encoded = Base64.encodeBase64(usernamePassword.getBytes());
            encoding = new String(encoded);

            urlc.setRequestProperty( "Authorization", "Basic " + encoding );
            urlc.setRequestMethod("POST");
            urlc.setUseCaches(false);
        return urlc;
    }

    public static HttpsURLConnection doHttpsPost(String msisdn, String actualPrice, String basePrice) throws MalformedURLException, Exception {

    System.out.println("dHTTPPost(): Start");
    String chargingServiceURL="https://10.5.45.111:6443/sdpchargingservice/http/charge";
    String strResponse = "";
    HttpsURLConnection urlc=getHTTPSConnection(chargingServiceURL);
    try{
        //get data from config file
        Properties prop = new Properties();
        prop.load(new FileInputStream("/vishnu/twss/config.properties"));

        System.out.println("HttpService :charge():Going to hit Charging Service..");
        Long currentMilis = System.currentTimeMillis();

        urlc.setRequestProperty("Keep-Alive", "300"); 
        urlc.setRequestProperty("Connection", "keep-alive"); 

        //set the keep aive in the system properties
        System.setProperty("http.keepAlive", "true");
        System.setProperty("http.maxConnections", "2000");

        urlc.setRequestMethod("POST");
        urlc.setRequestProperty("SOAPAction","");
        urlc.setRequestProperty("Content-Type","text/xml; charset=utf-8");
        urlc.setDoOutput(true);
        urlc.addRequestProperty("operation","debit");
        urlc.addRequestProperty("userId",msisdn); //CP to use his own msisdn
        urlc.addRequestProperty("contentId","Exam Results");
        urlc.addRequestProperty("itemName","Exam Results");
        urlc.addRequestProperty("contentDescription", "Exam Results"+currentMilis);
        urlc.addRequestProperty("contentMediaType","Exam Results");
        urlc.addRequestProperty("actualPrice",actualPrice);
        urlc.addRequestProperty("basePrice",basePrice);
        urlc.addRequestProperty("discountApplied","0");
        urlc.addRequestProperty("cpId","voicetap");
        urlc.addRequestProperty("eventType","Content Purchase");
        urlc.addRequestProperty("deliveryChannel","SMS");
        urlc.addRequestProperty("currency","INR");
        urlc.addRequestProperty("copyrightId","null");
        urlc.addRequestProperty("sMSkeyword","SMS");
        urlc.addRequestProperty("srcCode","606770");
        urlc.addRequestProperty("contentUrl","www.voicetap.com");
        urlc.addRequestProperty("copyrightDescription","Test Desc");
        System.out.println("going to hit service......");

       System.out.println(" urlc response  "+urlc.getResponseMessage());

       try{     
            System.out.println(urlc.getHeaderField("status"));
            String loggermsg = "MSISDN: "+prop.getProperty("userId") +
                    " Actualprice: "+prop.getProperty("actualPrice") +
                    " transactionId: "+urlc.getHeaderField("transactionId") +
                    " status: "+urlc.getHeaderField("status")+
                    " errorCode: "+urlc.getHeaderField("errorCode")+
                    " date: "+new java.util.Date();
          InputStreamReader isr = new InputStreamReader(urlc.getInputStream());
          BufferedReader in = new BufferedReader(isr);
          String inputLine;
          while ((inputLine = in.readLine()) != null){
            System.out.println(inputLine);
          } 
          in.close();
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("Execption raised during parsing SOAP-response :::" + e.getMessage());
        }
    }
    catch (Exception ex) {
        ex.printStackTrace();
        System.out.println("Error "+ex);
    }
    return urlc;
}
}
Vishnu
  • 3,899
  • 2
  • 18
  • 19
  • Hi tibo & Alex K I am new to stack overflow. I dont had idea about accept. Thanks for guidance – Vishnu Jun 05 '12 at 06:49

1 Answers1

0

HttpURLConnection already does connection pooling. You don't have to do anything about it except avoid calling dispose().

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thanks, So how can i improve the performance? Do i need to use multithreaded environment. – Vishnu Jun 04 '12 at 12:28
  • @Vishnu I've answered the question in your title. This is a new question, as is your third question about HttpClient. Please make up your mind. I don't know why you think multithreading would help, unless you are connecting to multiple URLs, which if true doesn't appear in your question. – user207421 Jun 04 '12 at 18:32
  • Thank EJP for your valuable comments. Actually above mentioned serviceURL takes 1.3 sec to respond, however i am getting approx 30-50 hits per/second. So i am not clear, how to handle it. If HttpURLConnection already does connection pooling then is multithreading is the solution for it? Plz help me – Vishnu Jun 05 '12 at 04:56
  • @Vishnu 'Is multithreading the solution' for what? You mentioned multi-threading in your question all right, but you didn't say why, and you haven't confirmed the suggestion in my comment above about multiple URLs. *If that's what you're doing,* I would multi-thread it. You need to make your question clear before it can be answered. – user207421 Jun 05 '12 at 07:42
  • @EJB I need to hit same url with different properties( like msisdn, basePrice). – Vishnu Jun 05 '12 at 07:55
  • @Vishnu Please edit your *question* to include all this missing information. If you need to do different things *at the same time,* use threads. You have still failed to make clear whether that is so or not. – user207421 Jun 05 '12 at 08:02
  • @EJB I am not good in english, but i tried to clear my question. Not is it make sence – Vishnu Jun 05 '12 at 08:41