URLConnection != Sockets

I am writing a servlet that reads content from some URLs, and uses regular expressions to get data from these URLs.
When I use URLConnection, everything goes ok, but when I use Sockets, in some URLs, I can't extract the data from it using regular expressions, because the data from the URLConnection sometimes differ from the data from the sockets. And sometimes I get unexpected results, like:
HTTP/1.1 302 Moved TemporarilyServer: Netscape-Enterprise/4.1Date: Fri, 28 Dec 2001 04:35:22 GMTLocation: http://www.uol.com.br/Content-length: 0Content-type: text/htmlConnection: close
What can I do to fix my code? Here is the code I am using:
USING SOCKETS::
import java.net.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class testurl extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
  throws IOException, ServletException
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
BufferedReader data;
String line;
StringBuffer buf = new StringBuffer();
URL url;
Socket httpSocket;
String tmp1 = "";
try {
url = new URL("http://www2.uol.com.br/cgi-bin/AT-examesearch.cgi?search=test");
httpSocket = new Socket(url.getHost(),url.getPort()==-1?80:url.getPort());
httpSocket.setSoTimeout(45000);
new DataOutputStream(httpSocket.getOutputStream()).writeBytes("GET " + url.getFile() + " HTTP/1.0\r\n\r\n");
data = new BufferedReader(new InputStreamReader(httpSocket.getInputStream()));
while ((line = data.readLine()) != null) {
  buf.append(line);
tmp1 = buf.toString();
data.close();
catch(MalformedURLException mue){
catch (UnknownHostException uhe){
catch (InterruptedIOException ioe){
catch (IOException ioe){
out.println(tmp1);
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
  throws IOException, ServletException
        doGet(request, response);
}USING URLCONNECTION::
      URLConnection conn = null;
      BufferedReader data;
      String line;
      StringBuffer buf = new StringBuffer();
      try {
        conn = new URL("http://www2.uol.com.br/cgi-bin/AT-examesearch.cgi?search=test").openConnection();
        conn.connect();
        data = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = data.readLine()) != null) {
          buf.append(line);
        tmp1 = buf.toString();
        data.close();
      } catch(MalformedURLException e) {
      } catch(IOException e) { }     
.

1. HttpUrlConnection sends header information to identify user-agent (Java <version>) and formats understood ("text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2") and makes HTTP/1.1 requests; you don't.
2. It is aware of and handles redirects by default (controlled via the set/getFollowRedirects accessors), you don't.
HTTP requires more than just connecting to port 80.

Similar Messages

  • Limitations of URLConnection/Socket - (bypassing firewall)

    I've made a chat program using a stand-alone server (ServerSocket) and Applets for the GUI. The Applet must send a new request and wait for a response from the server. The Applet requests are recorded in a Vector in the server (socket and in/out info), and (for now) any sent message is echoed to all connected Applets.
    I need to know the limitations of this method. It's excellent to bypass a firewall, but it's also a 1-cycle at a time method (not full-duplex).
    Will the server get bogged down eventually, missing requests and/or messages sent from Applets? Of course it works fine for just a few Applet connections, but what if there are 10,000 Applets sending/receiving data from the server? Is there a limit to the number of open sockets on the server side?
    This is extremely important, and I thank everyone in advance for reading this post.
    Mark S.

    I have some problemms too... Using the simple ServerSocket class it seams
    that the number of connections it's not unlimited (how it shuld be).
    My application stop responding over 40 connections... It's my applications
    fault or it's about the system?

  • Diffrence between socket connection and URLConnection

    hy friends,
    though, i know and often work on it but it might be more conceptual for me to know your perception.
    by the way, what are the main points which diffrentiate the connection between client and server using
    1) sokets which in tern using ClientSocket,ServerSocket... classes
    2) URL directly which in tern using HttpURLConnection,URLConnection...classes
    any help would greatly appreciated

    1) sokets which in tern using ClientSocket,ServerSocket... classesYou mean 'sockets', and 'Socket', not 'ClientSocket'. Sockets speak TCP.
    2) URL directly which in tern using HttpURLConnection,URLConnection...classesHttpURLConnection speaks HTTP which is an application protocol layered over TCP.

  • Java Pug-in 1.4.1_02 not closing sockets using URLConnection

    I am developing an applet that accesses a URL to get data to be displayed on the screen (Apache, mod_plsql). The problem is that when I execute the applet using "appletviewer" in my machine, each URLConnection shares only one socket connection to the WEB server. When the same applet is executed in the browser through the Java Plug-in 1.4.1_02, each URLConnection creates a new socket connection. Is there any bug? Is this a matter of configuration? Browser version? To test the applet I am using Forte for Java 4CE, JDK 1.4.1_02 (the same version as the Plug-in). I have tried many things already without success, there are no error messages in the server nor any exception on the applet. Both my machine and the server are Windows 2000 SP3.

    Have you found a solution to this? I'm having a similar problem with URLConnection always starting a new socket connection when run from within the Java Plug-In.

  • Socket error 10038 on URLConnection

    We put a Java 1.2.2 applet into production on our intranet starting in April. Of the more than 800 users (all running Windows and IE), 3 have been unsuccessful in getting it to work; the appliet will not make a connection to our application server via a URLConnection to a CGI. The error returned is a connection error, code = 10038, "Socket operation on a non-socket."
    This week the applet failed for two more of our users who had been using it successfully. They both reported that a Windows application (Remedy software, I think it is their Help Desk product) had been upgraded.
    Any ideas as to why our applet fails with the 10038 on a small number of machines? Or what other environmental factors (Winsock problems?, etc.) might cause the 10038 error as evidenced by the upgrade of another application?
    Stephen

    We have same problem with 10038 error. It appears after installing Ws2help.dll in C:\Windows\System. This dll was required by "trillian", a instant messenger software. The problem disappears after removing this library.

  • URLConnection vs socket

    I am just wondering what could be the difference in the results of the following two approaches. I am trying to load a web page from www.oanda.com. One approach is to read from the input stream associated with URLConnection object. Another one is to use socket and send the following request to
    the server
    GET /  HTTP/1.1
    User-Agent: Simple Web Client
    Host: localhost
    Content-type: text/html
    Connection: close
    Content-length: 0
    Accept: */*The first one loads the page correctly while the second one returns just <HTML><HEAD></HEAD><BODY></BODY></HTML>. The pages from other servers that I've tried are loaded correctly. Therefore this is probably something specific to the server. I am wondering what could be the difference between the two approaches. (The ultimate objective is to send POST requests using socket thus any suggestions how to fix the socket are very welcome).

    Some random HTTPClient code:
    PostMethod post = new PostMethod("http://www.someplace.com/url/to/your/form");
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.addParameter("param1", "value1");
    post.addParameter("param3", "value2");
    HTTPClient client = new HTTPClient();
    int status = client.executeMethod(post); //status is the HTTP response number
    String response = post.getResponseBodyAsString(); //You can also get it as a byte[] or InputStream
    System.out.println(response);
    {code}
    However, I'd definitely read a tutorial on it. And yes, I find the above a bit simpler when loading a lot of web pages. It adds that tiny bit of abstraction that makes things just that much easier.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Behaviour of UrlConnection differs from Socket.

    When I download url with UrlConnection it works ok, but reading with sockets an "HTTP/1.1 404 Object Not Found" message is returned. It is a mistery. Both variants produce the same request:
    GET http://idirector.media.ibeam.com/netshow/launch/video/music/000/000/242/242649.asx?playerid=playID%3D5DD600FF3E914B4587A5227B6A73C43B HTTP/1.1
    User-Agent: Java1.3.0_02
    Host: idirector.media.ibeam.com
    Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
    Proxy-Connection: keep-alive.
    The code is 100% working. Uncomment a line to get Socket version of resource download.
    import java.net.*;
    import java.io.*;
    class Clips {
      static BufferedReader connect() throws IOException {
        Socket s = new Socket("idirector.media.ibeam.com", 80);
        PrintStream ps = new PrintStream(s.getOutputStream());
        ps.println("GET http://idirector.media.ibeam.com/netshow/launch/video/music/000/000/242/242649.asx?playerid=playID%3D5DD600FF3E914B4587A5227B6A73C43B HTTP/1.1");
        ps.println("User-Agent: Java1.3.0_02");
        ps.println("Host: idirector.media.ibeam.com");
        ps.println("Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
        ps.println("Proxy-Connection: keep-alive");
        ps.println("");
        ps.flush();
        return new BufferedReader(new InputStreamReader(s.getInputStream()));
      public static void main(String[] args) throws Exception {
        URL yahoo;
        BufferedReader in;
        yahoo = new URL("http://idirector.media.ibeam.com/netshow/launch/video/music/000/000/242/242649.asx?playerid=playID%3D5DD600FF3E914B4587A5227B6A73C43B");
        in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
    //    in = connect();
        String inputLine;
        while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
        in.close();
    }My problem is that I'am writing a proxy but some resourses cannot be downloaded becouse of the resource cannot be found, while another proxies can. Sorry for so long lines, some text editors cannot copy them well.

    With sockets, did you try just
    GET /netshow/launch/video/music/000/000......
    instead of:
    GET http://idirector.media.ibeam.com/netshow/launch/video/music/000/000.......

  • Socket creation too slow versus URLConnection

    I'm trying to write a transparent proxy like polipo.
    Polipo is written in C and I want to have the same result in java.
    A simple program that can filter/monitor all connections created and closed by the browser.
    To do so, I've chosen to work with sockets, because that's the only way i know to read and write raw data to and from the browser in a completely transparent way.
    In this moment my code reads and writes every couple of request/response but I've noticed profiling it that the time needed to create the socket is a bottleneck.
    Using URLConnection to create the same connection I need much less time than sockets.
    When socket creation implies 50ms URLConnection implies only 1ms.
    I haven't still understand why.
    I don't want to reinvent the wheel and i've read some old post where this problem was known, but I haven't found the solution.
    Can anyone help me to understand if the approach is incorrect?

    Creating a socket with a host and port parameter implies actually creating the TCP connection.
    Creating a URLConnection just implies creating an object in memory. The TCP connection isn't created until you call getInputStream(), getErrorStream(), or getResponseCode().
    So your measurements are worthless.
    If creating TCP connections is taking excessive time, look to your network and your DNS system.

  • HttpUrlConnection, URLConnection, and Sockets for HTTP

    Suppose we want to send requests and receive documents over HTTP frequently. Is establishing direct connections and manually sending HTTP request by using Sockets faster than simply using a HttpUrlConnection instance?
    What if we want to establish persistent connections (HTTP Keep-Alive) ?

    Using raw sockets is probably slower than
    using HttpURLConnection, which runs a connection pool.Thanks for the tip.
    I searched the web for "Connection Pool" and read the first 4-5 results. As I understood, connection pools are a group of cached connections which resides on the server side in the database server or application server memory. Unfortunately I don't understand how HttpURLConnection runs a connection pool, or perhaps I didn't understand what a Connection pool really is! Would you please explain more?

  • Can some one give me clear answer how to set timeouts on URLConnection ?

    I am amazed why Sun did not specify a simple method like setReadTimeout
    on URLConnection or provide a way to get refernce to the underlying socket objet. By default the timeout is infinite!
    I am using JDK 1.4 and these appraoches:
    -Dsun.net.client.defaultConnectTimeout=<value in milliseconds>
    -Dsun.net.client.defaultReadTimeout=<value in milliseconds>
    also don't work.
    I do not have access to Socket object. Please help.
    I am using URLConnection in my client application on HTTPS and doing heavy load form POST processing. I tried
    Sockets as well but they don't work. URLConnection works perfectly fine except for the timeouts nightmare.

    OK this might sound crazy but you may have been onto it right from the start. I was having the exact same (frustrating) problem with the URLConnection waiting forever on a dead server and no way to terminate it. I tried something like what you said in your first post:
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
    and it worked. I played around with the number and it it was apparent to the naked eye that it was working (if you can believe that...).
    Of course, I'm using JDK 1.4.1_01 by now, so this might be different now.
    ttfn.

  • How to make a socket connection timeout infinity in Servlet doPost method.

    I want to redirect my System.out to a file on a remote server (running Apache Web Server and Apache Tomcat). For which I have created a file upload servlet.
    The connection is established only once with the servlet and the System.out is redirected to it. Everything goes fine if i keep sending data every 10 second.
    But it is required that the data can be sent to the servlet even after 1 or 2 days. The connection should remain open. I am getting java.net.SocketTimeoutException: Read timed out Exception as the socket timeout occurs.
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.
    Following is the coding to establish a connection with the Servlet.
    URL servletURL = new URL(mURL.getProtocol(), mURL.getHost(), port, getFileUploadServletName() );
    URLConnection mCon = servletURL.openConnection();
    mCon.setDoInput(true);
    mCon.setDoOutput(true);
    mCon.setUseCaches(false);
    mCon.setRequestProperty("Content-Type", "multipart/form-data");
    In the Servlet Code I am just trying to read the input from the in that is the input stream.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    byte [] content = new byte[1024];
    do
    read = in.read(content, 0, content.length);
    if (read > 0)
    out.write(content, 0, read);
    I have redirected the System.out to the required position.
    System.setOut(........);
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.

    I am aware of the setKeepAlive() method, but this can only used with the sockets. Here i am inside a servlet, have access to HTTPServletRequest and HTTPServletResponse and I don't know how to get access to the underlying sockets as the socket handling will be handled by the tomcat itself. If I am right there will be method in the apache tomcat 6.0.x to set this property. But till now I am not getting it.

  • Need Help in reading data from URLConnection in servlets

    hi i created GUI which sends d username n password to the servlets via URLConnection.n am sending the same to Server program via sockets.but when i read d data in the servlet am getting only null value...need help here....
    This is my button's ActionPerformed code
    private void LoginActionPerformed(java.awt.event.ActionEvent evt) {
    String uname = UserName.getText();
    char [] pwd = PassWord.getPassword();
    String pword = new String(pwd);
    try
    String url = "http://localhost:8080/MIMServlets/hit";
    URL ucon = new URL(url);
    URLConnection conn = ucon.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
              conn.setUseCaches (false);
    conn.setDefaultUseCaches (false);
    conn.setRequestProperty("Content-Type", "text/plain");
    System.out.println(uname);
         System.out.println(pword);
         PrintWriter out = new PrintWriter( conn.getOutputStream() );
    BufferedReader in = new BufferedReader(
    new InputStreamReader(
    conn.getInputStream()));
         out.print(uname);
    out.print(pword);
         out.close();
    String inputLine = in.readLine();
    Status.setText(inputLine);// TODO add your handling code here:
    }catch(MalformedURLException e)
    System.out.println("Exception"+e);
    catch(IOException e1)
    System.out.println("Exception"+e1);
    This is my Servlet code........
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class MIMServlets extends HttpServlet
    PrintWriter out,out1;
         BufferedReader in,in1;
         String host = "localhost";
         String fromServer = "";
         String username,password;
         int a;
         public void init()
    out=null;
    out1=null;
    public void doPost(HttpServletRequest request,HttpServletResponse
                   response)throws ServletException,IOException
              response.setContentType("text/html");
              out=response.getWriter();
              try{
              InetAddress address = InetAddress.getByName(host);
    Socket theSocket = new Socket(address, 4444);
    out1 = new PrintWriter(theSocket.getOutputStream(),true);
    in = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
    in1 = new BufferedReader(new InputStreamReader(request.getInputStream()));
              String username = in1.readLine();
              String password = in1.readLine();
    System.out.println(username);
              System.out.println(password);
    out1.println(username);
              out1.println(password);
              out1.println("Yahoo");
              out1.flush();
    while ((fromServer = in.readLine()) != null)
    out.println("From Server: " + fromServer);
              break;
         out1.close();
    in.close();
    theSocket.close();
         }catch(IOException e)
    System.out.println("Exception");
    System.exit(-1);
              public void destroy()
         out.close();
    thanks in advance.......

    Follow below example to using FM 'READ_TEXT'
    DATA  BEGIN OF i_tlines OCCURS 0.
            INCLUDE STRUCTURE tline.
    DATA  END   OF i_tlines.
    DATA: w_textname(70) TYPE c.
      w_textname = vbdkr-vbeln.
      CALL FUNCTION 'READ_TEXT'
        EXPORTING
          client                        = sy-mandt
          id                            = 'Z006'
          language                      = 'E'
          name                          = w_textname
          object                        = 'VBBK'
        TABLES
          lines                         = i_tlines.
      IF sy-subrc = 0.
        READ TABLE i_tlines INDEX 1.
        t_in-m1 = i_tlines-tdline.   "Now t_in_m1 will have the value
      ENDIF.
    Regards,
    SaiRam

  • SocketException during reads - JVM_recv in socket input stream read

    I am getting a SocketException when a Java applet talks to our
    WebLogic 7.0 server. The catch is that it only occurs at one site
    (that has very high T1 utilization, although latency is only ~60 ms)
    Our setup is such that the calls hit an Alteon load balancer, which
    then sends the request out to one of 4 IIS clustered servers, where it
    then is sent to one of 2 WL clustered servers. I figured latency
    would be the cause, but on IIS and on WL, the timeouts are set to
    several hundred seconds, so I am not quite seeing where the connection
    is being reset. To be honest, I really don't know if it is WL that is
    killing the connection, as nothing abnormal shows up in the WL log. I
    have seen similar problems in this group, though, although the stack
    traces never follow the same path mine does. I do have the following
    call stack from the Java plug-in console, though. Any ideas would be
    greatly appreciated.
    java.net.SocketException: Connection reset by peer: JVM_recv in socket
    input stream read
         at java.net.SocketInputStream.socketRead0(Native Method)
         at java.net.SocketInputStream.read(Unknown Source)
         at java.io.BufferedInputStream.fill(Unknown Source)
         at java.io.BufferedInputStream.read1(Unknown Source)
         at java.io.BufferedInputStream.read(Unknown Source)
         at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
         at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
         at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
         at sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
         at sun.net.www.protocol.http.HttpURLConnection.getHeaderFields(Unknown
    Source)
         at sun.plugin.net.protocol.http.HttpURLConnection.checkCookieHeader(Unknown
    Source)
         at sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
         at org.xxxx.abstracts.Controller.sendRequest(Controller.java:39)
         at org.xxxx.data.DataMediator.getDataNode(DataMediator.java:46)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Also, here is my code, although I can't see anything on the client
    side that seems off:
    public Object sendRequest( Object request, URL receiver ) throws
    Exception{
    Object response = null;
    URLConnection con = null;
    ObjectOutputStream out = null;
    ObjectInputStream in = null;
    try {
    con = receiver.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setDefaultUseCaches(false);
    con.setAllowUserInteraction(false);
    out = new ObjectOutputStream(con.getOutputStream());
    out.writeObject(request);
    out.flush();
    out.close();
    in = new ObjectInputStream(con.getInputStream());
    response = in.readObject();
    in.close();
    } catch (ClassCastException e) {
    if( out != null ){
    out.close();
    if( in != null ){
    in.close();
    } catch (Exception e) {
    if( out != null ){
    out.close();
    if( in != null ){
    in.close();
    throw e;
    return response;

    There is a known bug on earlier 1.3.1 releases with sockets on Windows 2k
    and XP. I don't remember all the details.
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "Keith Patrick" <[email protected]> wrote in message
    news:[email protected]...
    I'm getting the exception on the client, which is an XP machine, while
    the server is Win2K. I can't recall which, but either the applet or
    the server runs 1.3x while the other runs 1.4. I discounted that
    factor, though, as the problem only occurs on one site, which on all
    others it works fine.
    "Cameron Purdy" <[email protected]> wrote in message
    news:<[email protected]>...
    Exception is in the applet or on the server?
    Would one of those by any chance be running on W2K with JDK 131_01 orolder?
    >>
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "Keith Patrick" <[email protected]> wrote in message
    news:[email protected]...
    I am getting a SocketException when a Java applet talks to our
    WebLogic 7.0 server. The catch is that it only occurs at one site
    (that has very high T1 utilization, although latency is only ~60 ms)
    Our setup is such that the calls hit an Alteon load balancer, which
    then sends the request out to one of 4 IIS clustered servers, where it
    then is sent to one of 2 WL clustered servers. I figured latency
    would be the cause, but on IIS and on WL, the timeouts are set to
    several hundred seconds, so I am not quite seeing where the connection
    is being reset. To be honest, I really don't know if it is WL that is
    killing the connection, as nothing abnormal shows up in the WL log. I
    have seen similar problems in this group, though, although the stack
    traces never follow the same path mine does. I do have the following
    call stack from the Java plug-in console, though. Any ideas would be
    greatly appreciated.
    java.net.SocketException: Connection reset by peer: JVM_recv in socket
    input stream read
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.BufferedInputStream.fill(Unknown Source)
    at java.io.BufferedInputStream.read1(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
    at
    sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
    at sun.net.www.protocol.http.HttpURLConnection.getHeaderFields(Unknown
    Source)
    atsun.plugin.net.protocol.http.HttpURLConnection.checkCookieHeader(Unknown
    Source)
    atsun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
    Source)
    at org.xxxx.abstracts.Controller.sendRequest(Controller.java:39)
    at org.xxxx.data.DataMediator.getDataNode(DataMediator.java:46)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Also, here is my code, although I can't see anything on the client
    side that seems off:
    public Object sendRequest( Object request, URL receiver ) throws
    Exception{
    Object response = null;
    URLConnection con = null;
    ObjectOutputStream out = null;
    ObjectInputStream in = null;
    try {
    con = receiver.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setDefaultUseCaches(false);
    con.setAllowUserInteraction(false);
    out = new ObjectOutputStream(con.getOutputStream());
    out.writeObject(request);
    out.flush();
    out.close();
    in = new ObjectInputStream(con.getInputStream());
    response = in.readObject();
    in.close();
    } catch (ClassCastException e) {
    if( out != null ){
    out.close();
    if( in != null ){
    in.close();
    } catch (Exception e) {
    if( out != null ){
    out.close();
    if( in != null ){
    in.close();
    throw e;
    return response;

  • How to create HTTPS or secure Socket objects in JDK 1.4?

    I would like to see sample working code that shows creation
    of Sockets objects that work with HTTPS using JDK 1.4. I am doing
    a POST operation (form submission) on HTTPS URL. I must use Socket
    objects and cannot use URLConnection (I know URLConnection solves the problem automatically in JDK 1.4).
    Also sample code for POST operation would be appreciated.

    I wrote this a little while ago to test out Secure Sockets in 1.4. I assume you are doing the client since you are trying talk to a website or something like that, anyway this test class is tested and works, but you will have to clean it up.
    Pup
    import java.io.*;
    import java.security.*;
    import javax.net.ssl.*;
    public class HelloClientSSL {
        public static void main(String[] args) {
            try {
                int port = 8005;
                int tempport =0;
                if(args.length > 1) {
                    try {
                        tempport = Integer.parseInt(args[1]);
                        port = tempport;
                    catch (Exception e) {
                        System.out.println("Sorry this is not a valid number " + args[1]);
                        System.out.println("Using Default port 8005");
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());           
                SSLSocketFactory sslFact = (SSLSocketFactory)SSLSocketFactory.getDefault();
                SSLSocket s = (SSLSocket)sslFact.createSocket(args.length == 0 ? "127.0.0.1" : args[0], port);
                s.setEnabledCipherSuites(s.getSupportedCipherSuites());
                java.net.Socket n = (java.net.Socket) s;
                java.io.ObjectOutputStream OOS = new java.io.ObjectOutputStream(n.getOutputStream());
                BufferedReader in = new BufferedReader (new InputStreamReader(n.getInputStream()));
                String response = "";
                String temp = "This is reall cool and stuff\n";
                OOS.writeObject(temp);
                OOS.writeObject("Hello\n");
                while((response =in.readLine()) != null){
                    System.out.println("Socket message: " + response);
                in.close();
            } catch (Exception e) {
                System.out.println("Exception" + e);
                e.printStackTrace();
    }

  • 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;
    ******************************************************************************************

Maybe you are looking for