How to use URL class instead of Socket

Hi all. I am developing a small inventory control system for a warehouse.
I am suing a Java desktop application that connects to a servlet via Internet.
I have been searching the net how to use JSSE for my application since i am new to secure sockets and JSSE.
Since I havent implemented security In my current system yet, i am using URLConnection conn = url.openConnection(); to connect to a servlet.
However, in a good tutorial that I found about JSSE, sockets are used directly for connection, insted of URLCOnnection. They use the code like this: SSLSocketFactory sf = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket)sf.createSocket( host, port ); Since, using sockets is overly complex for me, I want to make use of the URLConnection class instead to keep it simple.
Could anyone please tell me how to make use of the URLConnection class to establish secure http connection.
by the way, the tutorial is here:
http://www.panix.com/~mito/articles/articles/jsse/j-jsse-ltr.pdf
thanks.

Here you go. The following code snippet allows you post data to http URL. If you have to do the same to https URL , please let me know.
OutputStream writeOut = null;
HttpURLConnection appConnection = null;
URL appUrlOpen = null;
//data to be posted.
String data = "This is the test message to post";
byte[] bytesData = this.data.getBytes();
appUrlOpen = new URL(""Your Servlet URL");
appConnection = (HttpURLConnection) appUrlOpen.openConnection();
appConnection.setDoOutput(true);
appConnection.setDoInput(true);
appConnection.setUseCaches(false);
appConnection.setInstanceFollowRedirects(false);
appConnection.setRequestMethod("post");
appConnection.setRequestProperty("Content-Type","application/text");
appConnection.setRequestProperty("Content-length", String.valueOf(bytesData.length));
writeOut=appConnection.getOutputStream();
writeOut.write(bytesData);
writeOut.flush();
writeOut.close();
String inputLine;
StringBuffer sb = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(appConnection.getInputStream()));
char chars[] = new char[1024];
int len = 0;
//Write chunks of characters to the StringBuffer
while ((len = reader.read(chars, 0, chars.length)) >= 0)
sb.append(chars, 0, len);
System.out.println("Response " + sb.toString());
reader.close();
sb=null;
chars = null;
responseBytes = null;
******************************************************************************************

Similar Messages

  • How to use URL class to execute a java class/app  on a remote machine?

    I am a beginner in Java networking and have a question about URL programming.
    How do I pass parameters to a java class/application over the web and then cause it to execute ? I then want to get the result back from the clas/app. The class/app resides on a remote machine and the protocol used is "http" protocol. OR all this is not possible through the URL and related classes ?

    How do I pass parameters to a java class/application over the web and then cause it to execute ? Using the HTTP protocl you can either perform a GET where the parameters are in the URL or a POST where the data is sent to the server with the request.
    The server must be setup as a web server to execute code based ojn a HTTP request. Using a web server with a JSP which contains the code to execute is the simplest way to do this.
    I then want to get the result back from the clas/app. The output of the JSP becomes in the data returned by the HTTP request.
    I would suggest looking for example on google.
    http://www.google.co.uk/search?q=java+http+request+tutorial
    Another option is to use RMI. The integration is tighter but it does not use the HTTP protocol.

  • How to use "url.openStream()" . What this function does?

    how to use "url.openStream()" . What this function does?
    Edited by: sahil1287 on Apr 16, 2009 10:02 PM

    http://java.sun.com/javase/6/docs/api/java/net/URL.html#openStream()
    http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html

  • How  to use url iview???

    how  to use url iview???
    HI all
    I need to use url iview as back button in the same page with saptransaction iview.
    url iview to used as back button to the home page.
    pl suggeest how to use url ivew....what sort of properties need to be  used.

    HI chander
    thank u for ur response
    I have done an  aplication in which  i have called sap transsaction ivew usind quick link property in .html(page) language.
    where we will be fetching saplogon server using this sap trans saction ivew into the portal frame work  .
    when i loging into the server and log off  with in the portal frame work i am not able to go to my aplication home page. since back/ forward link are disabled.
    atleast i want know how to enable those links.
    or else
    i thought to use url ivew along with sap transaction ivew with a  same page with diffrent layouts.but that is also fine.
    and one   more option  was
    i thought it to be used as pop up as so that when user  login and log off into the server  they will close  that seperate window.
    for that i have set the  ivew property
    "launch in a new window property As : display in a seperate head less portal window"
    but even that is also not working.
    i dont know y  that property is not working
    finally i have coded with java script , now i am able to open the portal in a seperate window but with headed portal.
    for that i have coded some thing like below mentioned.
    problem here is still i am getting the headed portal
    but i want head less portal.
    here headless in the sence i want it like the preview of the ivew.
    please help me in this regard how to get the head less portal when i click on the link.
    Regards
    Gayathri

  • When to use abstract classes instead of interfaces with extension methods in C#?

    "Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived classes when needed. In C#, however,
    this differentiating factor has been reduced by the recent introduction of extension methods, which enable implementations to be provided for interface methods. Another differentiating factor is that a class can inherit only one abstract class (i.e., there
    is no multiple inheritance), but it can implement multiple interfaces. This makes interfaces less restrictive and more flexible. So, in C#, when should we use abstract classes
    instead of interfaces with extension methods?
    A notable example of the interface + extension method model is LINQ, where query functionality is provided for any type that implements IEnumerable via
    a multitude of extension methods.

    Hi
    Well I believe Interfaces have more uses in software design. You could decouple your component implementing against interfaces so that
    you have more flexibility on changing your code with less risk. Like Inversion of Control patterns where you can use interfaces and then when you decide you can change the concrete implementation that you want to use. Or other uses for interfaces is you could
    use Interceptors using interfaces (Unity
    Interceptor) to do different things where not all of these is feasible or at least as straightforward using abstract classes.
    Regards
    Aram

  • How to use TableSorter class with DefaultTableModel

    Hi Friends
    Please tell me how to use TableSorter Class which is in the Java. Tutorials with DefaultTableModel.
    i saw in a thread there it was given that we have to pass the DefaultTableModel to the TableSorter Class.
    I tried to use like that. But i am getting Error Like Exception occurred during event dispatching:
    I am posting the part of Code where i use the DefaultTableModel
         private void displayavailablity(String selectedAuthor)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        String bname,bauthor,bcategory,bref1,bavail,bid;
                        int bref,mid,num;
                        rs = st.executeQuery("SELECT BId,BName,BAuthorName,BAuthorandPublisher,BCat FROM Books where BAuthorandPublisher='" +selectedAuthor+"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"NUMBER","BOOK NAME","AUTHOR","CODE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        TableSorter sorter = new TableSorter((DefaultTableModel)table.getModel());
                        rs.close();
                   catch(SQLException ex)
                        System.out.println("ERROR IS HERE");
                        ex.printStackTrace();
         }Please help me on this issue Otherwise Please give me some Sample coding to implement this sorting. with DefaultTableModel
    Thank you for your service
    Cheers
    Jofin

    I don't know about any TableSorter class, but I suppose you mean javax.swing.table.TableRowSorter.
    The TableRowSorter is to be attached to the JTable, not to the data model. Here's a cut'n'paste from the last time I used it:
    RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
    myTable.setRowSorter(sorter);
    And heres from the JDK1.6 documentation:
    TableModel myModel = createMyTableModel();
    JTable table = new JTable(myModel);
    table.setRowSorter(new TableRowSorter(myModel));
    Check out http://java.sun.com/javase/6/docs/api/javax/swing/table/TableRowSorter.html. I find it to be good documentation.

  • How to use multiple classes for each form

    Hi,
    I have created two forms using screen painter and now i want to use different classes for these two forms .
    I have declared the Sbo Connection in main class i.e. Set Application ,Connection Context() but while connecting to other classes
    for executing the code for that form SAP is not connected to that class.How to use multiple classes functionality i don't able to
    do that.Please provide some sample codes for that as it will be more helpful for me to understand.
    Thanks & Regards,
    Amit

    Hi Amit,
    In fact, its more advisable to use separate classes for every form that you use.  Have one common class, say, for eg., clsMain.cs which has all the connection and connectivity to other classes, wherein, the menu event and item event of this main class, will just be calling the menu / item event of other classes.
    The individual functionality of the child classes will be called from the item / menu event of the respective classes.
    Item event in clsMain.cs will be as below.
    private void oApplication_ItemEvent(string FormUID, ref SAPbouiCOM.ItemEvent pVal, out bool BubbleEvent)
                SAPbouiCOM.Form oForm;
                BubbleEvent = true;
                try
                    if ((pVal.FormTypeEx == "My_Form1Type") && (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD))
                        oForm = oApplication.Forms.GetForm("My_FormType", pVal.FormTypeCount);
                        NameSpace.Repots.ClsForm1.ClsForm1_ItemEvent(oApplication, oCompany, oForm, ref pVal, ref BubbleEvent);
                    if ((pVal.FormTypeEx == "My_Form2Type") && (pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD))
                        oForm = oApplication.Forms.GetForm("My_FormType", pVal.FormTypeCount);
                        NameSpace.Repots.ClsForm1.ClsForm2_ItemEvent(oApplication, oCompany, oForm, ref pVal, ref BubbleEvent);
    Now, in the individual classes, you can have their respective item events, which will be called from the main class, and the respective functionalities will occur.
    Hope this helps.
    Regards,
    Satish.

  • How to use ArraySequence class???

    Hi ,
    I'm a beginner in programing with java.. I found some troubles with it
    the trouble is HOW TO USE ArraySequence class,
    I need to read a word from the user and broken it down and store each letter in a rank of the ArraySequence,,
    I found an example that breaks a string into words ,,But I never found
    examples that fill an ArraySequence with a built-in types like int or double or char
    Can anybody please help me??!!!!
    some functions of ArraySequence take as parameter OR return (position ) class can you please tell me what does this class do??
    SORRY FOR MY LANGUAGE ,,I'M NOT NATIVE SPEAKER

    There is no ArraySequence class in the API.

  • How to use the class CL_CTMENU with the method DISABLE_FUNCTIONS

    Hi Friends,
    How to de-activate some functions in the Menu bar?
    Eg: - Sales document
                 Create
                 Change
                 Display
    I want to de-activate "Change"
    In other words: - How to use the class CL_CTMENU with the method DISABLE_FUNCTIONS in my program.
    Regards,
    Hari
    Edited by: Bhatlapenumarthy Hari Krishna on Jun 9, 2008 5:22 PM

    Krishna,
    It is not possible to deactivate the CHANGE option in themenu bar using the method disable_functions of cass CL_CTMENU. This method allows you to deactivate only the function codes of the CONTEXT MENU, which is available only when u press the left mouse button.
    U can use the SET PF-STATUS 'XXX' EXCLUDING fcodes option to disable the CHANGE.
    *****Reward points if useful
    Regards,
    Kiran Bobbala

  • How to use StreamTokenizer class ?

    i want to use StreamTokenizer class in my program so that when i read from a file i want to make tokens of words present in the file, but i dont know how to use this class in my program, as i didnt find any example which shows how to use StreamTokenizer class. Can nebody knows how to use it in a program ?

    Hi,
    here's some sample code of how to use the StreamTokenizer.
    in = new StreamTokenizer(
    new BufferedReader(
    new FileReader(fname)));
    You can iterate through the file with:
    while(in.nextToken() != StreamTokenizer.TT_EOF)
    when you call nextToken() ttype is filled with the type of token, you can't test ttype for what kind of token,
    test for word:
    if (in.ttype == StreamTokenizer.TT_WORD)
    test for word:
    if (in.ttype == StreamTokenizer.TT_WORD)
    I think you can grasp the rest in javadoc

  • How to use assistance class in WD4A?

    Hi SDN,
    Can you please tell me How to use assistance class in WD4A?
    Regards,
    Rahul

    Create a class that inherits the class cl_wd_component_assistance. By default, it will have the method if_wd_component_assistance~get_text, which is used to retrieve text elements defined in the class. You can also add any other methods to it, like accessing your data etc.
    In your wd4a component, in the main component overview screen, there will be a tetxfield for assistance class. define your class name there. You do not have to instantiate it separately. You can access the class methods using the object wd_assist, which will be created globally in your component.
    Regards
    Nithya

  • Can u  tell me any of you how to use Date class

    Can u tell me any of you how to use Date class. Please send me the source code.

    People won't send you the source code.
    Ask specific questions. You are very vague.
    Tell me how to build.

  • How to use an instance instead of the class itself

    I am building a program but have a problem.
    My program uses a controller class which instantiates a World-class. In the world class has a Vector I make a Vector in which I place all the elements in the world. (I also made an Element class from which all the objects that I put into this Vector extend.)
    Everything except for some methods in the controller class are declared public. I might need to use static, but I do not know how.
    // CONSTRUCTOR CONTROLLER CLASS
    world = new World ();  // instantiate one and only one world
    world.newElement (new Beamer ("beamer", 20. , 20.));  // use a selfwritten method to add a "Star Trek"-like
                              // beamer to the world. I give it a name and position.
    world.newElement (new Avatar ("avt", "beamer"));  // add an avatar which is "beamed up". so what I do is that I use the beamer for the beginposition of the avatar. However, and this is my problem, in the constructor of Avatar (see below) i need the beamer in world, but my compiler cant find world. I probably need to import my World or controller class, but even then: I do not understand how to use an instance (world is an instance. I cant use the World-class as the class does not contain the beamer element)
    public class Avatar extends Element {
         public Avatar (String n, String beamer){
              name = n;
              posx = world.named("beamer").getPosx; // the selfwritten method named finds the
                // element in the Vector that goes with the name. Any ideas to make this code better are welcome too.
              posy = world.named("beamer").getPosy;
    } Any ideas on how to solve this (common) problem in good coding are most welcome.

    I think you are best off if you use static methods and static fields only in your World class. That way you don't have to instantiate it and everyone has access to its methods. This would be then completely analogous to how you access methods and fields of the well-known class System (e.g. when you use System.out.println). This also has the advantage that you are guaranteed to have only one copy of the World.
    Here is an example of how your World class, Avatar class and main code would look like.
    Main code: (note the use of capital W in the name World, referring to class rather than instance).
    // no need to instantiate World, as we call its static methods only
    World.newElement (new Beamer ("beamer", 20. , 20.));
    World.newElement (new Avatar ("avt", "beamer"));  // add an avatar which is "beamed up". World class: (note the static keyword in front of the vector and the methods)
    public class World {
      private static Vector v;       // static field, only one copy of it ever exists
      public static void newElement(Element e)   // static method, can call without instantiating world
         v.addElement(e);
      public static Element named(String n)  // use to look up elements
         ... some code which goes through v and finds element named "n" ...
         ... return reference to that element ...
    }and finally the Avatar: (again note the use of reference to World as a class rather than instance)
    public class Avatar extends Element {
         public Avatar (String n, String beamer){
              name = n;
              posx = World.named("beamer").getPosx;
              posy = World.named("beamer").getPosy;
    } The above example is how I would implement it when you don't actually need instances of the World class.

  • How to use application class reference in the controller methods of BSP

    Hi,
    I have created a bsp application and also created an application class and assigned it to the application class. In the application class, I have created attribute TEXT type string(public and instance parameter).
    In the controller let's say main.do, I am trying to give a value to to the text by adding the following code.
    application->text = 'test'.
    I am getting syntax error saying field 'text' is unknown. It is not contained in one of the specified tables nor defined by DATA statement. 
    Please can someone let me know how to use the application class in the coding with an example. I couldn't find how exactly this has to be reference. Please help.
    Best regards
    Siva

    Hi,
    if you are having main controller and sub-controller then you may need to use below coding to use application class reference.
    *Data declaration
      DATA:  obj_cntrl        TYPE REF TO cl_bsp_controller2,
             obj_sub_cntrl   TYPE REF TO z_cl_sub_cntl,
             application TYPE REF TO z_cl_application.
    *Get the controller
      CALL METHOD obj_main_cntrl->get_controller   "obj_main_cntrl is the object of main controller
        EXPORTING
          controller_id       = 'SUB'   "Controller ID
        RECEIVING
          controller_instance = obj_cntrl  .
      obj_sub_cntrl ?= obj_cntrl  .
      application ?= obj_sub_cntrl ->application.
    or simply use below code in your controller method.
      application ?= me->application.
    Thnaks,
    Chandra

  • How to use outside Class in packed library plugins

    I have found the very useful article from Michael Lacasse (https://decibel.ni.com/content/docs/DOC-19176) on how to use packed library as plugins. This approach makes the most sense when you try to distribute additional code after your executable has already been installed.
    My problem is that when I try to use a class from the main code in a plugin, the plugins won't work anymore. Ideally, I would have liked the parent plugin-interface to inherit from a class used in the main code, or using the class as an input parameter of the plugin would be the next best thing.
    I got several errors, some at execution time (#1448) or at edit time ("This VI does not match other VIs in the method: connector pane terminal(s)"). I have settled to use clusters to pass data to the plugins.
    My question is: Is it possible to use a class defined in the main code in a packed-project-library, either inherited or as a parameter? If yes, do you have any example?
    Marc Dubois
    HaroTek LLC
    www.harotek.com
    Solved!
    Go to Solution.

    I should point out that it's important to use the copy THAT'S IN THE PPL, *-NOT-* the copy from your source.
    It will compile if you mix them together, but they aren't the same object, and won't share data.
    You should never refer to your source code for the class, except to build the PPL.
    (Consider using a separate project, to avoid temptation).
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

Maybe you are looking for

  • Need help setting up Macbook Pro and external hard drive(s)

    I apologize for the vague title but I was limited to so many characters. Here's my situation (sorry for being verbose, I just want to be thorough) Right now I have a Macbook Pro and a 500 GB external hard drive (Western Digital using USB 2.0 connecti

  • Steps to upgrade from 8i  to 10g

    i look for some documents about this topic 'steps to upgrade from 8i to 10g' but i couldn't find in the site... would you mind tell me where can i find a complete document , or if you can tell me in details please. thanks alot in advance

  • Date and Time calculation in the Service Module

    Dear all, I have quite of a challenge here and i need serious guidance from your side. My client is in services industry and requires to calculate the date and time when the service call as to be closed. Not only it depends on the contract type the s

  • DNS Advice Needed

    Is it possible or advisable to let a standalone webserver hosting a handful of websites to be it's own dns server - in terms of holding the authoritative records for the domains hosted? Thank you

  • Memory allocation error when burning in premiere elements 2

    I have premiere elements 2. I happily burnt a version of my dvd then suddenly it stopped burning and I had the above message during the burning section of the process. My computer has adequate memory to run this programme and nothing new has been add