Https with URLConnection class

when instantiating a URL object with protocol "https", i get a MalformedURLException. However, it works fine with "http".
anyone?

Following is an extract from this article.
http://java.sun.com/products/jsse/doc/guide/API_users_guide.html
Specifying an HTTPS Protocol Implementation
It is possible to access secure communications through the standard Java URL API. That is, you can communicate securely with an SSL-enabled web server by using the "https" URL protocol or scheme using the java.net.URL class.
In order to be able to do this, you need to have an "https" URLStreamHandler implementation and you must add the handler's implementation package name to the list of packages which are searched by the Java URL class. This is configured via the java.protocol.handler.pkgs system property. See the java.net.URL class documentation for details.
The JSSE 1.0.2 reference implementation provides an "https" URLStreamHandler implementation. Here is an example of how you would set the java.protocol.handler.pkgs property on the command line to indicate the JSSE 1.0.2 reference implementation's "https" URLStreamHandler:
java -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol
myApp

Similar Messages

  • How to use HTTPS with JSSE URLConnection in servlet

    Hi, I have a servlet that calls another servlet using the URLConnection class. This seems to work very well if I am using http. However when trying to call it using https using JSSE I get the following error:
    "javax.net.ssl.SSLHandshakeException: untrusted server cert chain."
    The following is the code that I am using in the servlet:
              java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
              System.getProperties().put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
              this.servlet = new URL(servletURL);
              URLConnection conServlet = servlet.openConnection();
    Both of these servlets are under IIS on my machine. I am able to execute each of the servlets from the browser using https directly. Does this sounds like an SSL certifcate problem or is that something in the Java code? Any ideas greatly appreciated.

    Hi,
    Perhaps you can create your own trust manager. I've found this example in another newsgroup: (please note that this example trusts everyone, but you can modify the trust manager as you wish)
    if (putUrl.startsWith("https"))
      //set up to handle SSL if necessary
      System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
      System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");
      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      //use our own trust manager so we can always trust
      //the URL entered in the configuration.
      X509TrustManager tm = new MyX509TrustManager();
      KeyManager []km = null;
      TrustManager []tma = {tm};
      SSLContext sc = SSLContext.getInstance("ssl");
      sc.init(km,tma,new java.security.SecureRandom());
      SSLSocketFactory sf1 = sc.getSocketFactory();
      HttpsURLConnection.setDefaultSSLSocketFactory (sf1);
    m_url = new URL (putUrl);
    class MyX509TrustManager implements X509TrustManager {
    public boolean isClientTrusted(X509Certificate[] chain) {
      return true;
    public boolean isServerTrusted(X509Certificate[] chain) {
      return true;
    public X509Certificate[] getAcceptedIssuers() {
      return null;
    }Hope this helps,
    Kurt.

  • How do i open a web page with VeriSign Class 3 Extended Validation SSL SGC SS CA certfificate i can't open web pages with this, how do i open a web page with VeriSign Class 3 Extended Validation SSL SGC CA certfificate i can't open web pages with this

    how do i open a web page with VeriSign Class 3 Extended Validation SSL SGC SS CA ?

    Hi
    I am not suprised no one answered your questions, there are simply to many of them. Can I suggest you read the faq on 'how to get help quickly at - http://forums.adobe.com/thread/470404.
    Especially the section Don't which says -
    DON'T
    Don't post a series of questions in  a single post. Splitting them into separate threads increases your  chances of a quick answer.
    PZ
    www.pziecina.com

  • Report of posted Deprecation with ASSET CLASS

    Hi Gurus,
    We require a depreciation simuation report with Asset class as mandatory one.
    Could you please tell me path and t-code for the above said report.
    Regards,
    Praveen.

    Hi Praveen,
    You mentined before you wanted to view depreciation simulation, for this RASIMU02 is the report to use.
    However, if you want to see depreciation planned /and or posted you can use the Asset Balance RABEST_ALV01. If you click on the indicator  "current book value" you will see the actually posted depreciation and current Netbook Value. Also in this report you can enter the Asset Class in the selection parameters.
    Regarding viewing the note I forwarded to you previously: you can view it via the SAP Portal - http://help.sap.com/. If you go to SAP ERP tab, you will see on the right hand side pannel a link to SAP Notes. Here you can view any note.
    I hope this helps further.
    Kind regards,
    Brigitte

  • Problems with importing classes in Java

    Hello,
    i have some problems with a simple project.
    The structure is like this:
    web-inf/classes/databeans/loginexistinguserform.java
    web-inf/classes/formactions/loginexistinguseraction.java
    loginexistinguserform.java :
    package databeans;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionError;
    import org.apache.struts.action.ActionMapping;
    import javax.servlet.http.HttpServletRequest;
    public class LoginExistingUserForm extends ActionForm
         String userid;
         String password;
         public String getUserid(){return userid;}
         public void setUserid(String newUserid){userid=newUserid;}
         public String getPassword(){return password;}
         public void setPassword(String newPassword) {password=newPassword;}
         public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){
              ActionErrors errors=new ActionErrors();
              if(this.userid==null||this.userid.equals(""))
                   errors.add("user",new ActionError("error.userid.required"));
              if(this.password==null||this.password.equals(""))
                   errors.add("pass",new ActionError("error.password.required"));
              return errors;
    }loginexistinguseraction.java
    package formactions;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import databeans.LoginExistingUserForm;
    public class LoginExistingUserAction extends Action
         public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
         throws IOException, ServletException
              LoginExistingUserForm loginData=(LoginExistingUserForm)form;
              if(loginData.getUserid().equals("Admin")&&loginData.getPassword().equals("Parola"))
                   return mapping.findForward("successLogin");
              else
                   return mapping.findForward("failureLogin");
    }I can complie succesfully loginexisitinguserform.java but problems appears when i want to compile the second file, loginexistinguseraction.java with command: javac loginexistinguseraction.java
    C:\ApacheGroup\Tomcat\webapps\PersonalWeb\WEB-INF\classes\formactions>javac loginexistinguseraction.java
    loginexistinguseraction.java:10: package databeans does not exist
    import databeans.LoginExistingUserForm;
    ^
    loginexistinguseraction.java:17: cannot find symbol
    symbol : class LoginExistingUserForm
    location: class formactions.LoginExistingUserAction
    LoginExistingUserForm loginData=(LoginExistingUserForm)form;
    ^
    loginexistinguseraction.java:17: cannot find symbol
    symbol : class LoginExistingUserForm
    location: class formactions.LoginExistingUserAction
    LoginExistingUserForm loginData=(LoginExistingUserForm)form;
    ^
    3 errors
    I have the CLASSPATH variable setup tu C:/Sun/Appserver/lib/j2ee.jar
    Can someone help me ? Thank you in advance !

    Thank you very much ! It worked. I'm really new in Jav a programming.
    Now i have encoutered another problem. When i want to login, and enter user name and password i am redirected to a login.do page, instead of Welcome.jsp
    Here is Login.jsp:
    <%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@page contentType="text/html; charset=ISO-8859-1"%>
    <html>
    <head><title>Login Form</title></head>
    <body>
    <html:errors/>
    <html:form action="/login">
    <table border="0" width="200">
    <tr>
         <td>User Name:</td>
         <td><html:text property="userid" maxlength="13"/></td>
    </tr>
    <tr>
         <td>Password:</td>
         <td><html:password property="password" maxlength="13"/></td>
    </tr>
    </table>
    <br />
    <html:submit value="Login"/>
    </html:form>
    </body>
    </html>and here is struts-config.xml :
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE struts-config PUBLIC
              "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
              "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
    <struts-config>
    <!--========================beans for HTML form data=======================-->
    <form-beans>
         <form-bean name="loginBean" type="databeans.LoginExistingUserForm"/>
    </form-beans>
    <!--========================Action Mappings================================-->
    <action-mappings>
         <action path="/login" type="formactions.LoginExistingUserAction" name="loginBean" input="/Login.jsp" scope="session">
              <forward name="succesLogin" path="/pages/Welcome.jsp" redirect="true"/>
              <forward name="failureLogin" path="/pages/Diverse.jsp" redirect="true"/>
         </action>
    </action-mappings>
        <message-resources parameter="MessageResources" />
    </struts-config>

  • Https with client authentication handshake_failure

    Hi everyone. I hope anyone could help me. I have a client class 1 certificate from verisign (digital id) which is needed for https service request. I have installed it on Internet Explorer and it works fine:
    1) Internet Explorer ask me to trust in https server certificate.
    2) I accept the server certificate
    3) Internet Explorer ask me for select which client certificate send to server.
    4) I select my verisign client certificate
    5) Https server returns an xml with the response of the service.
    Now I have to implement this behaviour in Java. I have exported the client certificate to a .pfx file from Internet Explorer. Now I use this file directly as my key store. Then I used Internet Explorer to export server certificate as a .cer file and imported it into cacerts. The fact is that no matters what kind of transformation on the client certificate nor what validations i disable: I always get "Received fatal alert: handshake_failure" exception when trying to do in.readLine() (where in comes from BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));).
    I couldn't guess that connecting to a https server with client certificate was so difficult. I have read lots of examples and documentation, that always drive me to implement the same code.
    Sincerely, I don't use to ask in forums when having the first problems, but this time I'm really frustrated.
    Thanks in advance for any answer.

    Hi Rana da,
    If you want to use Https, make sure Https service must be activated in the system. Check Tcode: SMICM for HTTPS status.
    Have a look at below link
    Sender SOAP Adapter: HTTPS with Client Authentication

  • How to read a xml file with StringReader class

    Hi,
    I need to read a XML document with StringReade class. My aplication receives an absolute path but this doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need to do it as the frist way.
    Thanks

    Hi,
    I need to read a XML document with StringReade class.
    My aplication receives an absolute path but this
    doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need
    to do it as the frist way.
    Thankstake a look at this link:
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/2a_echo.html

  • Update query with CL_SQL_STATEMENT class

    Hi all,
    I'm trying to execute an update query with ADBC classes in order to modify two parameters (n_doc and processed) from a row with the following instructions:
          l_con_ref = cl_sql_connection=>get_connection( 'DB_7879' ).
          l_stmt_ref = l_con_ref->create_statement( ).
         CONCATENATE 'update' gv_table ' set n_doc= ? processed = ''X'' where id_ordn = ? '  INTO l_stmt SEPARATED BY space.
          GET REFERENCE OF materialdocument INTO l_dref.
          l_stmt_ref->set_param( l_dref ).
          GET REFERENCE OF ps_zmm_mov-id_ordn INTO l_dref.
          l_stmt_ref->set_param( l_dref ).
          l_stmt_ref->execute_update( l_stmt ).
    However, I got the error ORA-0933: SQL command not properly ended. I guess this error occurs because I am trying to update two parameters with a single query since using the following CONCATENATE instruction
         CONCATENATE 'update' gv_table ' set n_doc= ? where id_ordn = ? '  INTO l_stmt SEPARATED BY space.
    results ok.
    Does anybody know if it is possible to modify two parameters with only one update query with ADBC classes?
    Thank you in advance!

    Hi Suhas,
    Based on Oracle, I see it conforms almost completely ISO/IEC 9075 ([Oracle and Standard SQL|http://download.oracle.com/docs/cd/B10501_01/server.920/a96540/ap_standard_sql.htm#10293])
    UPDATE seems to conform completely [UPDATE SET clause|http://download.oracle.com/docs/cd/B10501_01/server.920/a96540/statements_108a.htm#2087215]
    So using a comma to separate columns is true for every SQL language that conforms ISO/IEC 9075
    Sandra
    PS: of course SAP's "Open SQL" language does not conform at all

  • Problems with inner classes in JasminXT

    I hava problems with inner classes in JasminXT.
    I wrote:
    ;This is outer class
    .source Outer.j
    .class Outer
    .super SomeSuperClass
    .method public createrInnerClass()V
         .limit stack 10
         .limit locals 10
         ;create a Inner object
         new Outer$Inner
         dup
         invokenonvirtual Outer$Inner/<init>(LOuter;)V
         ;test function must print a Outer class name
         invokevirtual Outer$Inner/testFunction ()V
    .end method
    ;This is inner class
    .source Outer$Inner.j
    .class Outer$Inner
    .super java/lang/Object
    .field final this$0 LOuter;
    ;contructor
    .method pubilc <init>(LOuter;)V
         .limit stack 10
         .limit locals 10
         aload_0
         invokenonvirtual Object/<init>()V
         aload_0
         aload_1
         putfield Inner$Outer/this$0 LOuter;
         return
    .end method
    ;test
    .method public testFunction ()V
         .limit stack 10
         .limit locals 10
         ;get out object
         getstatic java/io/PrintStream/out  java/io/PrintStream;
         aload_0
         invokevirtual java/lang/Object/getClass()java/lang/Class;
         ;now in stack Outer$Inner class
         invokevirtual java/Class/getDeclaringClass()java/lang/Class;
         ;but now in stack null
         invokevirtual java/io/PrintStream/print (Ljava/lang/Object;)V
    .end methodI used dejasmin. Code was equal.
    What I have to do? Why getDeclatingClass () returns null, but in dejasmin code
    it returns Outer class?

    Outer$Inner naming convention is not used by JVM to get declaring class.
    You need to have proper InnerClasses attribute (refer to http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html#79996)
    in the generated classes. Did you check using jclasslib or another class file viewer and verified that your .class files have proper InnerClasses attribute?

  • Issue with JSPs with inner classes (bug)

    FYI:
    Turning on Versioning in the registry (Disable=0) JSPs with inner classes causes the following IllegalAccessException...
    This has been confirmed with SP3 and SP4 with our testing...
    14/Jan/2002 13:26:24:4] error: Exception: SERVLET-run_failed: Failed in running template: /NASApp/fortune/foo.jsp, java
    lang.IllegalAccessError: try to access class jsp.APPS.fortune.foo$foobar from class jsp.APPS.fortune.foo
    xception Stack Trace:
    ava.lang.IllegalAccessError: try to access class jsp.APPS.fortune.foo$foobar from class jsp.APPS.fortune.foo
    at jsp.APPS.fortune.foo._jspService(foo.java:78)
    at org.apache.jasper.runtime.HttpJspBase.service(Unknown Source)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown Source)
    at com.netscape.server.servlet.servletrunner.ServletRunner.callJSP(Unknown Source)
    at com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callJspCompiler(Unknown Source)
    at com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callUri(Unknown Source)
    at com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callUriRestrictOutput(Unknown Source)
    at com.netscape.server.servlet.platformhttp.PlatformRequestDispatcher.forward(Unknown Source)
    at com.netscape.server.servlet.jsp.JSPRunner.service(Unknown Source)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown Source)
    at com.netscape.server.servlet.servletrunner.ServletRunner.execute(Unknown Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.thread.ThreadBasic.run(Native Method)
    at java.lang.Thread.run(Thread.java:479)
    Looking for work around....
    Cheers,
    Martin Gee

    I do not see why you would use two sorts.
    And what is the issue exactly by the way? Errors?
    So, the records before the Merge Join need to come sorted, to achieve this simply tick:
    Arthur My Blog

  • Please help with simple Classes understanding

    Working further to understand Class formation, and basics.
    At the Java Threads Tutorial site:
    http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    Goal:
    1)To take the following code, and make it into 2 seperate files.
    Reminder.java
    RemindTask.java
    2)Error Free
    Here is the original, functioning code:
    import java.util.Timer;
    import java.util.TimerTask;
    * Simple demo that uses java.util.Timer to schedule a task
    * to execute once 5 seconds have passed.
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class Reminder {
        Timer timer;
        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        class RemindTask extends TimerTask {
            public void run() {
                System.out.println("Time's up!");
                timer.cancel(); //Terminate the timer thread
        public static void main(String args[]) {
            new Reminder(5);
            System.out.println("Task scheduled.");
    }Here is what I tried to 2 so far, seperate into 2 seperate files:
    Reminder.java
    package threadspack;    //added this
    import java.util.Timer;
    import java.util.TimerTask;
    * Simple demo that uses java.util.Timer to schedule a task
    * to execute once 5 seconds have passed.
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class Reminder {
        Timer timer;
        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        public static void main(String args[]) {
            new Reminder(5);
            System.out.println("Task scheduled.");
    }and into
    RemindTask.java
    package threadspack;  //added this
    import java.util.Timer;
    import java.util.TimerTask;
    import threadspack.Reminder; //added this
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class RemindTask extends TimerTask
    Timer timer; /**here, I added this, because got a
    "cannot resolve symbol" error if try to compile w/out it
    but I thought using packages would have negated the need to do this....?*/
         public void run() {
                System.out.println("Time's up!");
                timer.cancel(); //Terminate the timer thread
    }After executing Reminder, the program does perform, even does the timing, however, a NullPointerException error is thrown in the RemindTask class because of this line:
    timer.cancel(); //Terminate the timer thread
    I am not sure of:
    If I have packages/import statements setup correctly
    If I have the "Timer" variable setup incorrectly/wrong spot.
    ...how to fix the problem(s)
    Thank you!

    Hi there!
    I understand that somehow the original "Timer" must
    be referenced.
    This is a major point of confusion for me....I
    thought that when importing
    Classes from the same package/other packages, you
    would have directly
    access to the variables within the imported Classes.I think you have one of the basic points of confussion. You are mixing up the concept of a "Class" with the concept of an "Object".
    Now, first of all, you do not need packages at all for what you are trying to do, so my advice is you completely forget about packages for the moment, they will only mess you up more. Simply place both .class files (compiled .java files) in the same directory. Your program is executing fine, so that indicates that the directory in which you have your main class file is being included in your classpath, so the JVM will find any class file you place there.
    As for Classes/Objects, think of the Class as the map in which the structure of a building is designed, and think of the Object as the building itself. Using the same technical map the architect defines, you could build as many buildings as you wanted. They could each have different colors, different types of doors, different window decorations, etc... but they would all have the same basic structure: the one defined in the technical map. So, the technical map is the Class, and each of the buildings is an object. In Java terminology, you would say that each of the buildings is an "Instance" of the Class.
    Lets take a simpler example with a class representing icecreams. Imagine you code the following class:
    public class Icecream{
         String flavor;
         boolean hasChocoChips;
    }Ok, with this code, what you're doing is defining the "structure" of an icecream. You can see that we have two variables in our class: a String variable with the description of the icecream's flavor, and a boolean variable indicating whether or not the icecream has chocolate chips. However, with that code you are not actually CREATING those variables (that is, allocating memory space for that data). All you are doing is saying that EACH icecream which is created will have those two variables. As I mentioned before, in Java terminology, creating an icecream would be instantiating an Icrecream object from the Icecream class.
    Ok, so lets make icrecream!!!
    Ummm... Why would we want to make several icecreams? Well, lets assume we have an icecream store:
    public class IcecreamStore{
    }Now, we want to sell icecreams, so lets put icecreams in our icecream store:
    public class IcecreamStore{
         Icecream strawberryIcecream = new Icecream(); //This is an object, it's an instance of Class Icecream
         Icecream lemonIcecream = new Icecream(); //This is another object, it's an instance of Class Icecream
    }By creating the two Icecream objects you have actually created (allocated memory space) the String and boolean variable for EACH of those icecreams. So you have actually created two String variables and two boolean variables.
    And how do we reference variables, objects, etc...?
    Well, we're selling icecreams, so lets create an icecream salesman:
    public class IcecreamSalesMan{
    }Our icecream salesman wants to sell icecreams, so lets give him a store. Lets say that each icecream store can only hold 3 icecreams. We could then define the IcecreamStore class as follows:
    public class IcecreamStore{
         Icecream icecream1;
         Icecream icecream2;
         Icecream icecream3;
    }Now lets modify our IcecreamSalesMan class to give the guy an icecream store:
    public class IcecreamSalesMan{
         IcecreamStore store = new IcecreamStore();
    }Ok, so now we have within our IcecreamSalesMan class a variable, called "store" which is itself an object (an instance) of the calss IcecreamStore.
    Now, as defined above, our IcecreamStore class will have three Icecream objects. Indirectly, our icecream salesman has now three icecreams, since he has an IcecreamStore object which in turn holds three Icecream objects.
    On the other hand, our good old salesman wants the three icecreams in his store to be chocolate, strawberry, and orange flavored. And he wants the two first icecreams to have chocolate chips, but not the third one. Well, here's the whole thing in java language:
    public class Icecream{ //define the Icecream class
         String flavor;
         boolean hasChocoChips;
    public class IcecreamStore{ //define the IcecreamStore class
         //Each icecream store will have three icecreams
         Icecream icecream1 = new Icecream(); //Create an Icecream object
         Icecream icecream2 = new Icecream(); //Create another Icecream object
         Icecream icecream3 = new Icecream(); //Create another Icecream object
    public class IcecreamSalesMan{ //this is our main (executable) class
         IcecreamStore store; //Our class has a variable which is an IcecreamStore object
         public void main(String args[]){
              store = new IcecreamStore(); //Create the store object (which itself will have 3 Icecream objects)
              /*Put the flavors and chocolate chips:*/
              store.icecream1.flavor = "Chocolate"; //Variable "flavor" of variable "icecream1" of variable "store"
              store.icecream2.flavor = "Strawberry"; //Variable "flavor" of variable "icecream2" of variable "store"
              store.icecream3.flavor = "Orange";
              store.icecream1.hasChocoChips = true;
              store.icecream2.hasChocoChips = true;
              store.icecream3.hasChocoChips = false;
    }And, retaking your original question, each of these three classes (Icecream, IcecreamStore, and IcecreamSalesMan) could be in a different .java file, and the program would work just fine. No need for packages!
    I'm sorry if you already knew all this and I just gave you a stupid lecture, but from your post I got the impression that you didn't have these concepts very clear. Otherwise, if you got the point, I'll let your extrapolate it to your own code. Should be a pice of cake!

  • Problem-Writing datas to a Servlet thro' URLConnection class

    Hi,
    Iam trying to post some string data to a servlet.
    The servlet reads 2 parameters from url.And reads the xml string message thro post method.
    So in the client program, I added those parameters to the URL directly like this,
    "http://localhost/servlet/test?action1=value1&action2=value2" ,and created url object .
    And using URLConnection iam trying to post the xml string.
    But the servlet does not read the parameter values.Is my approach is correct?
    client code:
    package test;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Testxml{
    public static void main(String ars[])
    String XML="<?xml version='1.0'?><Test><msg>test message</msg></Test>";
    String server="http://localhost/servlet/test";
    String encodeString = URLEncoder.encode("action1") + "=" + URLEncoder.encode("something1")+"&"+URLEncoder.encode("action2") + "=" + URLEncoder.encode("something2");
    try{
         URL u = new URL(server+"?"+encodeString);
         URLConnection uc = u.openConnection();
         uc.setDoOutput(true);
         uc.setUseCaches(false);
         uc.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
         OutputStream out = uc.getOutputStream();
         PrintWriter wout = new PrintWriter(out);
         wout.write(alertXML);
         wout.flush();
         wout.close();
         System.out.println("finished");
         catch(Exception e) {
         System.out.println(e);
    Servlet code:
    package test;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class test extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
         performTask(req, res);
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
         performTask(req, res);
    public void performTask(HttpServletRequest request, HttpServletResponse response) {
         try{
    String action1=request.getParameter("action1");
    String action2=request.getParameter("action2");
    if(action1.equals("something1") && action1.equals("something2") )
         ServletInputStream in = request.getInputStream();
         byte[] buffer = new byte[1024];
         String xmlMsg = "";
         int len = in.read(buffer,0,buffer.length);
         if(len>0)
         while (len > 0 ){
                   xmlMsg += new String(buffer,0,len);
                   len = in.read(buffer);
         System.out.println("xml : "+xmlMsg);
    This is not working.Even,it does not invoke servlet.Is this approach is correct?.
    Thanx,
    Rahul.

    Hi,
    Did you get the answer to your problem? I am facing the same problem, so if you have the solution, please share the same.
    TIA
    Anup

  • How to launch a browser with URLConnection content

    Hi,
    I'm new in Java programming, trying to write a Java application to send
    something to server and get response through HTTP. By following some tutorial material, I did
    import java.net.*;
    import java.io.*;
    public class URLConnectionReader {
        public static void main(String[] args) throws Exception {
            URL yahoo = new URL("http://www.yahoo.com/");
            URLConnection yc = yahoo.openConnection();
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    yc.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();
    }And got the source HTML. But how can I launch a default browser and send the header and HTML to the browser?
    Thanks.

    Hi,
    Thanks for the solutions. I'm more interested in the 2nd solution.
    However, when I tried it, the thread never returns from ss.accept().
    Here is the code I wrote. Can you tell me what I did wrong?
    Thanks.
    import java.net.*;
    import java.io.*;
    public class URLConnectionReader {
       public static void main(String[] args) throws Exception {
          URL url = new URL("http://www.yahoo.com");
          HtmlRelay relay = new HtmlRelay(url);
          relay.run();
          Runtime.getRuntime().exec("mozilla http://localhost:8080");
    class HtmlRelay extends Thread
      URL url;
      public HtmlRelay(URL u) { url = u; }
      public void run()
         try {
            URLConnection urlc = url.openConnection();
            BufferedReader in = new BufferedReader(
                                   new InputStreamReader(
                                   urlc.getInputStream()));
            final ServerSocket ss = new ServerSocket(8080);
            System.out.println(ss.toString());
            Socket accept = ss.accept();
            System.out.println(accept.toString());
            OutputStreamWriter os = new
    OutputStreamWriter(accept.getOutputStream());
            BufferedWriter ou = new BufferedWriter(os);
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                ou.write(inputLine);
                System.out.println(inputLine);
            ou.flush();
            ou.close();
            in.close();
         } catch (Exception e) {
             e.printStackTrace();
    }

  • [svn:bz-4.0.0_fixes] 20641: Update BlazeDS 4.0. 0_fixes branch to be able to run regressions with a class deserialization validator .

    Revision: 20641
    Revision: 20641
    Author:   [email protected]
    Date:     2011-03-07 09:14:03 -0800 (Mon, 07 Mar 2011)
    Log Message:
    Update BlazeDS 4.0.0_fixes branch to be able to run regressions with a class deserialization validator.
    Modified Paths:
        blazeds/branches/4.0.0_fixes/qa/apps/qa-regress/build.xml
    Added Paths:
        blazeds/branches/4.0.0_fixes/qa/apps/qa-regress/WEB-INF/flex/services-config.mods.validat ors.xml

    Remove this 3rd party add-on. Cooliris.
    0x20bd000 - 0x20befff com.cooliris.safariplugin ??? (1.7) /Library/InputManagers/Cooliris/Cooliris.bundle/Contents/MacOS/Cooliris
    Go here for a Glims update.
    http://www.machangout.com/

  • Why does page-break-before get replaced with br class hcp10?

    why does <br style="page-break-before: always;"> get replaced with <br class="hcp10">
    This issue only occurs when generating an HTML Help CHM file.

    An alternative method can be found in Item 23 at http://www.grainge.org/pages/snippets/snippets.htm#content.
    Are you saying the code in the source file gets changed? I suspect you mean target files but how are you identifying the change in a CHM? Is the change causing a problem?
    See www.grainge.org for RoboHelp and Authoring tips
    @petergrainge

Maybe you are looking for

  • Dial up Connection using External Modem in Solaris Intel Version

    Hi How to Install a modem in Solaris 7 Intel version and how to make a Dial Up Connection Using this external Modem. Can any one Help me.... send your reply to [email protected] Thanks in Advance .... Vinod.

  • J1939 Transport Protocol NI-CAN

    Are there any examples available for how to deal with multipacket J1939 CAN messages as per SAE J1939-21 5.10.3? I need to be able to read and the DM1 message in extended J1939.

  • How to set width to be same as screen size?

    Dear all I want to set the width of my view elements to be same as that of screen size, so that if a user with low resolution monitor runs it, or if a user with high resolution monitor runs it, both see the same. I tried setting the width to 100%. Bu

  • Photo's are continuing to be emailed

    I just updated my iPhone and sent a photo to myself. I got a message saying the the photo failed to be delivered yet even when it said that, the email of the picture went through. Now my phone is continuing to email me the picture. It has sent it abo

  • HT1338 Mountain Lion stops downloading at 41.3 mb's. Shows calculating and does not move on!

    Trying to download Mountain Lion on a Mac mini and it is stopping at 41.3 Mb's. It shows "calculating" but does not move on beyond that stage! Version 10.6.8 is the current OS... Any suggestions?