Communication with servlet using HTTPURLConnection

Hi Again,
well..trying to connect to a servlet using the HTTPURLConnection class.
but the servlet is found (as i have put a system.out in init method of the servlet and that gets printed correctly).my problem is that the doget method does not get invoked.
following is the code:
client side:
public class test
public test()
ObjectOutputStream outs=null;
try
URL url = new URL("http://127.0.0.1:7001/DataFetchServlet");
HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
System.out.println(urlcon.toString());
urlcon.setRequestProperty("Content-Type","application/octet-stream");
urlcon.setRequestMethod("GET");
urlcon.setDoInput(true);
urlcon.setDoOutput(true);
urlcon.setUseCaches(true);
outs = new ObjectOutputStream(urlcon.getOutputStream());
String str = new String("hello");
outs.writeObject(str);
ObjectInputStream inp = new ObjectInputStream (urlcon.getInputStream());//********************
outs.flush();
outs.close();
catch(Exception e)
     e.printStackTrace();
//******************** THIS LINE GIVES A FILENOTFOUND EXCEPTION
I am sure the servlet is found before the object is written but after the getInputStream it throws the excpetion..
can anyone help?????
THanx in advance

urlcon.connect();

Similar Messages

  • Communicating with Servlets....

    hi!
    Wat are all the different ways in which the JSP used to communicate with Servlet?
    Thanx,
    Rgds,
    Sasi

    Jsp page communication with Servlets....
    web.xml -- Servlets loaded during application startup
    struts config -- Servlet mapping (w.r.t struts).
    and u can import servlets in jsp and can use it... there are so many possible ways of using servlets coz jsp pages inturn convert into servlets and got executed.....

  • Communication with database using TCP sockets connection

    Hi all,
    I am bit of a newbie when it comes to databases. In a project I realised over te passed few weeks, I communicated with an 11g database using an application I created with VS Express. It uses an ODBC connection. I now want to connect a PLC to the same database. These PLC's don't have the ability to install an ODBC client so I need something different.
    I am easily able to open a TCP socket on the PLC and send data from there. I would like to know if I can start a TCP sockets connection with our 11g server and send all queries directly. The other (already suggested) option would be to have the PLC connect to a PC that reads this information and hands it over to the ODBC connector, but that would mean I need an extra PC just to 'translate'.
    I have been searching these forums for socket, TCP and more and feel it is possible, but I need a good document as a reference to show/tell me how it's done.
    Thanks in advance,
    Marijn

    The TCP/IP interface to Oracle is undocumented (and hugely complex anyway). You'll need to use a higher layer iterface or setup your own infrastructure.
    We need more information about what is available to you inside the PLC.
    Can you use Java? If so, perhaps use thin JDBC?
    Can you sent HTTP requests? If so you could set up your own Web services to handle this.
    If you can only use C or C++, Oracle has interfaces there too.. it's called OCI (Oracle Call Interface) and thats as close to the networking layer as you can get.
    Finally if you can use .NET Oracle has a Fully Managed Oracle Data Provider for .NET that you could use.
    But if all you can do is super low level network access and none of the above then you will need to set up an intermediary as you mentioned.

  • How can I use URLConnection to use applet communication with servlet?

    I want to send a String to a servlet in applet.I now use URLConnection to communicat between applet and servlet.
    ====================the applet code below=========================
    import java.io.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.net.*;
    //I have tested that in applet get data from servlet is OK!
    //Still I will change to test in applet post data to a servlet.
    public class TestDataStreamApplet extends Applet
    String response;
    String baseurl;
    double percentUsed;
    String total;
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    private String encodedValue(String rawValue)
         return(URLEncoder.encode(rawValue));
    =========================The servlet code below=====================
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class DataStreamEcho extends HttpServlet
    {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          res.setContentType("text/plain");
          PrintWriter out = res.getWriter();
          Runtime rt = Runtime.getRuntime();
          out.println(rt.freeMemory());
          out.println(rt.totalMemory());
          response.setContentType("text/html; charset=GBK");     
          request.setCharacterEncoding("GBK");
          PrintWriter out = response.getWriter();
          HttpSession session=request.getSession();
          ServletContext application=this.getServletContext();
          String currenturl=(String)session.getAttribute("currenturl");
          out.print(currenturl);
    =============================================================
    I have done up,but I found the program don't run as I have thought.
    Can you help me to find where is wrong?Very thank!

    You are trying to pass the current URL to the servlet
    from the applet, right?
    Well, what I put was correct. Your servlet code is
    trying to read some information from session data.
    request.getInputStream() is not the IP address of
    anything...see
    http://java.sun.com/products/servlet/2.2/javadoc/javax
    servlet/ServletRequest.html#getInputStream()
    Please read
    http://www.j-nine.com/pubs/applet2servlet/Applet2Servle
    .htmlNo,you all don't understand I.
    I want to send an Object to the server from a applet on a client.not url only.I maybe want to send a JPEG file instead.
    All I want is how to communicate with a servlet from an applet,send message to servlet from client's applet.
    for example,Now I have a method get the desktop picture of my client .and I want to send it to a server with a servlet to done it.How can I write the applet and servlet program?
    Now my program is down,But can only do string,can't not done Object yet.Can anyone help me?
    =======================applet=============================
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    con.connect();
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    =======================servlet=============================
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         response.setContentType("text/html; charset=GBK");
    //request.setCharacterEncoding("GBK");
    PrintWriter out = response.getWriter();
    HttpSession session=request.getSession();
    ServletContext application=this.getServletContext();
    //String currenturl=(String)session.getAttribute("currenturl");
    String currenturl=(String)request.getParameter("currenturl");
    out.print(currenturl);
    File fileName=new File("c:\\noname.txt");
    fileName.createNewFile();
    FileOutputStream f=new FileOutputStream(fileName); //I just write the String data get from
    //applet to a file for a test.
    byte[] b=currenturl.getBytes();
    f.write(b);
    f.close();
    }

  • Applet not communicating with servlet when given ip address (not localhost)

    I have a strange problem with my applet -
    I have a java applet and a Tomcat server running. I am able to communicate between the applet
    and a servlet on the server (sending strings from applet to servlet, for example..) when the
    URL that I write in the applet is -
    "http://localhost:8080/ProjectName/ServletName "
    BUT - when instead of that "localhost" I insert my ip address, it throws the exception:
    java.net.ConnectException: Connection refused: connect
    in the line -
    urlConn.getOutputStream(); (urlConn is the HttpURLConnection that I created with the URL)
    also, I did port forwarding (I have a router)
    so that 8080 port will be directed to my computer, and tested the forwarding, and it does work.
    Does anybody know why there is a problem?
    Thank you.. :)

    >
    well, in the final version of the project the applet will be signed.. >Uh-huh..
    >
    but, I got tired of signing it every time I edited the code, so now I just simply run it as a "java applet" project
    from the eclipse.. NOT as a signed jar..>Eclipse has Ant built in. Write a script that will compile/build/sign the jar for you, then build it to the point of being signed for every test run. (Just today I was making some changes to a signed applet project that does just that - I probably built it 25 times before I was happy with the changed code - not a problem.)
    >
    you think that's the problem ?>Yep. Not that I provide support for Eclipse, nor know how it goes about launching applets (trusted or sandboxed).

  • Communication with Servlets

    Hi all,
    This is my Clint
    private void getdeleteText(){
            String d[][] = null;
            try{
                java.net.URL urlServlet = new java.net.URL("http://localhost:8080/servlet/GetChatText?g="+group+"");
                java.net.URLConnection connect = urlServlet.openConnection();
                connect.setDoOutput(true);
                connect.setDoInput(true);
                connect.connect();
                System.out.println("done 1");
                java.io.ObjectInputStream in = new java.io.ObjectInputStream(connect.getInputStream());
                System.out.println("done 2");
                Object o = in.readObject();
                System.out.println("done 3");
                d=(String[][])o;
                System.out.println("done 4");
                System.out.println(d[0][0]);
                System.out.println("done 5");
            }catch(Exception e){
                System.out.println(e);
        }This is my servlet
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {   
            PrintWriter out = response.getWriter();
            String [][] d = null;
            group = request.getParameter("g");
            try{
                Class.forName("org.gjt.mm.mysql.Driver");
                Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/okweb?user=okwebuser&password=okwebuser");
                Statement statement = conn.createStatement();
                ResultSet rs = statement.executeQuery("SELECT color,size,chat,date FROM chatdata WHERE groupid = '"+group+"';");
                out.println("1");
                rs.last();
                int r = rs.getRow();
                rs.beforeFirst();
                d = new String [4][r];
                r=0;
                out.println("2");
                while(rs.next()){
                    d[0][r] = rs.getString("color");
                    d[0][r] = rs.getString("size");
                    d[0][r] = rs.getString("chat");
                    d[0][r] = rs.getString("date");
                    out.println(rs.getRow());
                statement.close();
                conn.close();
            }catch(Exception e){
                //PrintWriter out = response.getWriter();
                out.println(e);
                out.close();
            //PrintWriter out = response.getWriter();
            out.println(d[0][0]);
            out.close();
            ObjectOutputStream os = new ObjectOutputStream(response.getOutputStream());
            os.writeObject(d);
            os.flush();
            os.close();
        }This is the error I am getting
    run-single:
    done 1
    java.io.StreamCorruptedException: invalid stream header
    My problem is how my application can get the data taken from MYSQL database by the servlet
    I want to view this data in my application
    This application is not an applet. It is a class that extends JFrame
    Thanks you

    1:
    get it working passing text
    2:
    get it working passing a simple object
    3:
    then get it working using your example below
    Notes:
    You are try to mix text and objects
    PrintWriter out = response.getWriter();
    ObjectOutputStream os = new ObjectOutputStream(response.getOutputStream());This is not thread safe
    group = request.getParameter("g");You are rewriting to the same place
    d[0][r] = rs.getString("color");
    d[0][r] = rs.getString("size");
    d[0][r] = rs.getString("chat");
    d[0][r] = rs.getString("date");

  • Communicating with servlet's?

    Hello,
    I am planning to a write a servlet which will include several methods for adding to a database, searching for records and amending records.
    The adding, search and amending will each involve separate html or jsp pages which will include the post method.
    I just wondered how best I could tell the servlet which html/jsp page is posting to the servlet?
    Is using something like addrecord.jsp?action=ADD
    Widely used, or are there better methods?
    Thank you

    Thanks
    Rather than using addrecord.jsp?action=ADD,
    do you think its better to input a hidden input in the html or jsp
    <input type="hidden" name="ACTION" value="ADD"/>

  • Communication with OTM using SOA

    Hello,
    I am new to SOA and Fusion. I am trying to use the OTM webservice to insert records in the OTM Database.
    I have an external system reading an XML file. Using mediator to map the external XML to the OTM webservice WSLD. When I look in the OTM side, it seems like the XML generated by JDeveloper is not what OTM is expecting.
    How can I find the XML built based in the mappings in mediator?
    Thanks

    I'm having the same sort of issue. I can open and see the wsdl and I believe it should be running finE but getting an internal system error. Hope someone an help...

  • Communicating with Crestron using tcp/ip sockets

    Greetings...
    I trying to finish a desktop application written in Java that connects to an automation controller(Crestron) via sockets (TCP/IP). My main problem is that the connection is constantly going down. I have a thread that is always running to check if the connection is up, when it's brocken just puts it up again.
    Then i have another thread that's always running also to get the data that the
    Crestron controller sends me.
    The connection is broken usually by receiving a null.
    Is there any tip to solve this kind of trouble?
    The java app. is client and the Crestron is a server. Also i'm running the app. in Windows XP.
    It's a fix ip and the port is 4444.
    Also if anyone has experience of making software that interects with Crestron Controllers, please tell me something.
    Thanks for the help

    Sorry, but if your connection keeps getting dropped and your client does not close the connection then there is only one source: the controller itself is closing the connection. It may be some kind of timeout that is causing that the connection is closed. In any way, it is most likely not java but hardware / setting related.

  • Applet failed to communicate with servlet for https, on tomcat5.0+apache2.0

    Hi
         I have a problem, we have a tomcat5.0 and apache 2.0 with jk connector, and an application where an applet comunicate to servlet.
    we need to set the ssl , the apache is configured with the ssl( openssl,).
    when I run the application with standalone tomcat with ssl
    connector (port 8443)enable, it runs fine for both http and https.
    i use httpsURLconnection for https communication from applet to servlet.
    But at production envoirment (Tomcat 5.0 , apache 2.0 and j connector with ssl enable at apache) it fails for https, all the jsps runs properly, but the applet isn't communicating with servlet. can anyone guess what is the problem.
    the exception dump is
    ava.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 401 SSL Connection Not Granted"
         at sun.net.www.protocol.http.HttpURLConnection.doTunneling(Unknown Source)
         at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
         at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
         at com.blu.HttpMessage.sendGetMessage(HttpMessage.java:65)
         at com.blu.HttpMessage.sendGetMessage(HttpMessage.java:38)
         at com.blu.applet.ServerDAO.sendDummyRequest(ServerDAO.java:66)

    Make sure your deployment is using a supported network configuration, we do not support running under localhost. Your SGD  server needs a valid DNS name configured.
    See
    2.1. SGD Server Requirements and Support
    for more details

  • Communicate with servlet after using Java Web Start?

    Is it possible to communicate with servlet to get data back and forth
    after using Web Start to download the client application?
    The demos come with Java Web Start are applications which are
    standalone, don't need communicate with the servlet on Web server
    after being launched. I am wondering if it is possible, and how (HTTP
    & JAX-RPC)?
    Thanx in advance.

    I've done this using HTTP. I get the server and port from the codebase:
    BasicService bs = null;
    try {
    bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
    String codeBase = bs.getCodeBase().toString();
    and use the java.net.HttpURLConnection and java.net.URL classes to send HTTP parameter values to the servlet and to receive results from the HttpURLConnection's input stream.

  • VB Client communicating with a Java servlet

    Hi,
    I have a java servlet and I would like to have a VB application communicating with the servlet.
    Can I do it ? and if yes, how to do it.
    Thanks in anticipation,
    Ayana

    The VB client can open an internet or Http connection to the servelet, send a request and parse the response. We've done it here but I don't know exactly which ActiveX control the VB guy uses.
    Also look into using webservices.

  • Servlet Communication with Java WebStart

    Hi there,
    we have an application that works fine with Java WebStart whenever we start it in a local area network. But from outside the LAN the application cannot communicate to it's servlets. I use the codebase IP address with the servlet runner's port (http://<codebase IP>:port/) as URL for servlet communication, but the application's request never reaches the servlets.
    My question is now, if anyone had the same or a similar problem with servlet communication using Java WebStart, or if anyone knows, if that might be a problem with proxy configuration.
    The servlet runner we use, is JServ from Sun (JSDK2.0) and the webserver where it is running on is not behind a firewall or a proxy, but the client PC with the web start application is.
    Thanks,
    Katja

    Thank you for your early reply. But I think, that's not the problem.
    I get no security error and the webserver is identified the same way it is in the jnlp file. Also my application is not running in the Sandbox. My assumption is, that the http-request to the servlet does not go through the proxy server between my PC and the PC the servletrunner is running on.
    I wonder if I have to configure my application to use a proxy server for communication with the servlets instead of the direct http-request to the servlet runner?

  • Sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loop

    sir i have given lot of effort but i am not able to solve my problem either with notifiers or with occurence fn,probably i do not know how to use these synchronisation tools.

    sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loopHi Sam,
    I want to pass along a couple of tips that will get you more and better response on this list.
    1) There is an un-written rule that says more "stars" is better than just one star. Giving a one star rating will probably eliminate that responder from individuals that are willing to anser your question.
    2) If someone gives you an answer that meets your needs, reply to that answer and say that it worked.
    3) If someone suggests that you look at an example, DO IT! LV comes with a wonderful set of examples that demonstate almost all of the core functionality of LV. Familiarity with all of the LV examples will get you through about 80% of the Certified LabVIEW Developer exam.
    4) If you have a question first search the examples for something tha
    t may help you. If you can not find an example that is exactly what you want, find one that is close and post a question along the lines of "I want to do something similar to example X, how can I modify it to do Y".
    5) Some of the greatest LabVIEW minds offer there services and advice for free on this exchange. If you treat them good, they can get you through almost every challenge that can be encountered in LV.
    6) If English is not your native language, post your question in the language you favor. There is probably someone around that can help. "We're big, we're bad, we're international!"
    Trying to help,
    Welcome to the forum!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How to use JNI with Servlets

    Hi
    i was trying to do some example with JNI. I can use JNI with standalone Java application but I just cannot figure out how I can use JNI with Servlet.
    Can some one show me a sample code using JNI with Servlets.
    thanks very much

    hi,
    I am also facing the same problem,
    when I am using JNI with stand alone application it works fine but when i tried to use it with a servlet It gives unsatisfied linker error
    stack: java.lang.UnsatisfiedLinkError: createSocket
         at RelayConnector.createSocket(Native Method)
         at RelayServlet.doGet(RelayServlet.java:70)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.iplanet.server.http.servlet.NSServletRunner.invokeServletService(NSServletRunner.java:891)
         at com.iplanet.server.http.servlet.NSServletRunner.Service(NSServletRunner.java:458)
    It seems i have to do some path settings in my iplenet web server.
    If some one have faced the problem i would be glad to know the solution for this, i am literally bugged up,....

Maybe you are looking for