Writing/reading HTTP with plain sockets

Hello,
I�m trying to send an HTTP request and read response with a plain socket, not URLConnection.
My code below is not working - bufferedReader.readLine() returns null.
If I change to URLConnection everything works as expected.
What is wrong in my code?
Thanks in advance.
public static void main(String[] args) throws IOException {
        /* -- THIS CODE WORKS --
        URL url = new URL("http://localhost:8080");
        URLConnection urlConnection = url.openConnection();
        OutputStream outputStream = urlConnection.getOutputStream();
        InputStream inputStream = urlConnection.getInputStream();
        // Tomcat is running on localhost port 8080
        Socket socket = SocketFactory.getDefault().createSocket("localhost", 8080);
        OutputStream outputStream = socket.getOutputStream();
        InputStream inputStream = socket.getInputStream();
        // send request
        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
        writer.write("GET /");
        writer.flush();
        // read response
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder strBuilder = new StringBuilder();
        String str;
        while ((str = bufferedReader.readLine()) != null) {
            strBuilder.append(str);
        // print response
        System.out.println(strBuilder);
        socket.close();
    }

Your HTTP request-line(s) syntax is quite wrong.
Learn them at w3.org site.

Similar Messages

  • How do I use HTTPS with iMQ 2.0?

    Our business requirement mandates that we have to use tunneling in a SECURE way, i.e. we have to use HTTPS tunneling.
    Certainly this requires JMQ client code to open SSL socket instead of plain socket and also requires Web server to be configured and provides some management function to deal with
    I like to believe that we are not the only one asking such a feature. Is it doable with JMQ? Is this in the work?

    Deploying the JMQ2.0 HTTP Tunneling servlet on an https url will enable a
    secure connection from the client to the webserver. However, the tunneling
    servlet connection to the broker in JMQ2.0 is via a regular TCP connection and
    not via SSL.
    In our next major release we are adding the feature that provides a secure
    connection right from the client through the tunneling servlet (https) and on
    to the broker via SSL.
    We will (soon) have a beta version available.

  • HTTP(S) vs Sockets/SecureSockets - Can I use HTTP(s)?

    Good Day,
    I'm writing client/server, currently using Sockets (actually Secure Sockets, but I don't think SSL actually enters into the overall question). In order to not worry about complaints from firewalls or proxies, it would seem easiest to instead be using HTTP(S) so we look just like a browser and web server.
    However, it appears using the Java APIs you cannot avoid the open-request-response-close paradim, i.e. there is no way to keep the connection open (no persistence).
    I can put "connection: keep-alive" in the mime header, but Java apparently forces me to close the input stream to send (i.e. POST) the client transmission, which closes the connection.
    Is there a way (JDK 1.4) to keep an Http(s)UrlConnection open for continuous communication? The reason I care btw is because it is a heavily interactive data entry application, and response speed is crucial.
    Or is it possible I am worrying about nothing because the overhead of opening/closing the Http(s)UrlConnection is minor? (I am assuimg the TCP/IP connection and the SSL session remain open regardless, and it is just the Java open/close UrlConnection overhead). I am thinking about how to test the various scenarios, but most of that is still ahead of me, and it's always useful to get other experienced comments.
    Thanks in advance... Roger
    p.s. I'm also worried that even if my client and my server think the connection is persistent, some proxy in the pipe might think otherwise. Is that an issue?

    Have u got ur doubt cleared? lf no, l've a soln.
    u cant retain the same urlconnection for many req-res pairs.
    one conn is for one communication only. u cant keep the conn alive.
    lt takes much time for first secure conn. lf it is in a loop, next subsequent conn takes very less
    time. if u already know the no.of data to be sent, use a loop send the data with the same conn object.
    --Rams                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Accessing/Writing/Reading Tape/Compact Discs from Java

    Hi,
    Does Java provide any API for reading/writing files on Tapes/Compact Discs?
    Or is there any repository or API for the same?
    Ud highly appreciate to any pointers for the same.
    TIA,
    Regards,
    Prashanth Babu.

    From Unsupported Features and APIs:
    Unsupported Feature
    Alternative
    Remote invocations with a transport protocol other than HTTPS (including plain text HTTP).
    Not applicable.
    One alternative could be to create a web service that you can call from JCS.
    Jani Rautiainen
    Fusion Applications Developer Relations
    https://blogs.oracle.com/fadevrel/

  • Right way to communicate with a socket server (TCP/IP)

    Hi,
    I used to write data from my J2ME socket client to a J2EE socket server with writeUTF(). In this way I can send (and receive) directly Strings.
    When I need an XML file I ask the server with something like os.writeUTF(GIVE_ME_XML_FILE) and I use an XML parser with this socket InputStream.
    I was wondering if it's the right way to proceed ....?
    How do you guys communicate with a server when you need "to talk" a lot ? Do you use only HTTP requests or (if you are allowed to) do you use Socket with writeUTF ?
    Just to know if I'm completely wrong....and if I gonna have unsolicited issues ...
    Thanks..

    AdrienD wrote:
    When I need an XML file I ask the server with something like os.writeUTF(GIVE_ME_XML_FILE) and I use an XML parser with this socket InputStream.
    I was wondering if it's the right way to proceed ....?No, it is not. Read the writeUTF api docs, and you'll know why!
    How do you guys communicate with a server when you need "to talk" a lot ? Do you use only HTTP requests or (if you are allowed to) do you use Socket with writeUTF ?There is answer to this question. it al depends on what data gets send where, how often, and how large..

  • Help with SSL SOCKETS

    hi,
    i seem to have a problem with establishing an ssl socket between 2 machines. This problem has to do with certificates as the runtime error i get specifies.
    So i figured out there must be a concept that i'm misssing.
    So why do i have to place a certificate on my client? how can i generate it? where do i place it?
    Can anyone please provide me with a sample code that establishes an sslsocket connection.
    thnx a million

    A good place to start is:
    http://java.sun.com/j2se/1.4.1/docs/guide/rmi/socketfactory/SSLInfo.html
    There is a code example, but you will also need to follow the guide in the other link below to create the required key files.
    Don't base your knowledge of SSL RMI sockets solely on what I say here, as I'm fairly new to this so I may express myself wrong. But here is a 30,000 foot overview of what I did to get them to work:
    If you are using RSA on your SSL connection, a public and private key are required. For this to work, you must create a key (keystore) via Java's "keytool.exe" tool using the '-genkey' option (the keystore should eventually reside on your server). You will then create a certificate from that keystore using the '-export' option of the keytool. Lastly, you will import the certificate into your client's store of accepted certificates (the file java\lib\security\cacerts) via the '-import' option of keytool.
    For a full description, you need to read:
    http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html
    the section from this page on using keytool:
    http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html#CreateKeystore
    The example shows using a new custom file for the truststore, but I imported the certificate into Java's cacerts file instead. I was unable to find the certificate if it was not in this file, but I very well may have been doing something wrong.

  • Https with JSSE

    Hi,
    I am trying to write a simple client to connect to a https server.
    I have a .crt and a .key files generated with openssl for the server.
    As I understand I need to use those somehow to make a connection to the server. Otherwise I will always get "unable to find valid certification path to requested target".
    How can I do that.
    PS: If that's not the problem, plz, tell me what is then.
    Thank you.

    hi,
    user URL( "https","www.verisign.com","443","",new
    com.sun.net.ssl.internal.www.protocol.https.Handler()); to create url.
    thanks
    kiran
    "Junaid" <[email protected]> wrote in message
    news:3cc84396$[email protected]..
    >
    I'm writing an Https client, running within WebLogic. Can I use Sun's JSSEimplementation
    instead of WebLogic's? I set the Sun JSSE provider at position 1, as wellas setting
    the protocol handler to Sun's implementation. However my client program(running
    within WebLogic) still seeems to be using WebLogic's SSL (and https)implementations.
    Is there a way to NOT use WebLogic's SSL implementation?
    Thanks!

  • 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

  • PROTOCOL_ERROR line 627 of URL.cpp unexpected EOF reading HTTP status

    Hello,
    I'm having a problem getting the NSAPI plugin talking with the WLS6.1sp3 Application
    server.
    The iPlanet Server logs the error:
    *******Exception type [PROTOCOL_ERROR] raised at line 627 of URL.cpp
    Thu Oct 31 10:20:03 2002 got exception in sendRequest phase: PROTOCOL_ERROR [line
    627 of URL.cpp]: unexpected EOF reading HTTP status at line 1048
    Thu Oct 31 10:20:03 2002 Failing over after sendRequest exception
    The Application Server logs:
    <Oct 31, 2002 10:20:03 AM MST> <Error> <HTTP> <Connection failure
    java.lang.NullPointerException
    at weblogic.servlet.internal.ServletRequestImpl.setField(ServletRequestImpl.java:1733)
    at weblogic.servlet.internal.RequestParser.parse(RequestParser.java:254)
    at weblogic.servlet.internal.MuxableSocketHTTP.dispatch(MuxableSocketHTTP.java:355)
    at weblogic.socket.PosixSocketMuxer.deliverGoodNews(PosixSocketMuxer.java:455)
    at weblogic.socket.PosixSocketMuxer.processSockets(PosixSocketMuxer.java:384)
    at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:24)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    Thanks in advance!
    Steve

    FYI, this was determined to be a bug in WebLogic 6.1sp3. BEA provided us with a
    patch.
    "Steve Wall" <[email protected]> wrote:
    >
    Hello,
    I'm having a problem getting the NSAPI plugin talking with the WLS6.1sp3
    Application
    server.
    The iPlanet Server logs the error:
    *******Exception type [PROTOCOL_ERROR] raised at line 627 of URL.cpp
    Thu Oct 31 10:20:03 2002 got exception in sendRequest phase: PROTOCOL_ERROR
    [line
    627 of URL.cpp]: unexpected EOF reading HTTP status at line 1048
    Thu Oct 31 10:20:03 2002 Failing over after sendRequest exception
    The Application Server logs:
    <Oct 31, 2002 10:20:03 AM MST> <Error> <HTTP> <Connection failure
    java.lang.NullPointerException
    at weblogic.servlet.internal.ServletRequestImpl.setField(ServletRequestImpl.java:1733)
    at weblogic.servlet.internal.RequestParser.parse(RequestParser.java:254)
    at weblogic.servlet.internal.MuxableSocketHTTP.dispatch(MuxableSocketHTTP.java:355)
    at weblogic.socket.PosixSocketMuxer.deliverGoodNews(PosixSocketMuxer.java:455)
    at weblogic.socket.PosixSocketMuxer.processSockets(PosixSocketMuxer.java:384)
    at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:24)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    Thanks in advance!
    Steve

  • Http client------ XI  (via HTTP with SSL),

    hi forum,
    we have a http client that sends a http erquest to XI, by using sap/xi/adapter_plain
    service,  i mean plain http adapter
    but for scurity reasons i need HTTPS communication,
    can u tell me how to enable HTTPS (HTTP with SSL) communiaction in the same scenario,
    http client------>XI  (via HTTP with SSL)

    hi sudeep,
    u need to create a comm ch of adapter type http n set the security level there.
    refer this for help:
    http://help.sap.com/saphelp_nw04/helpdata/en/14/80243b4a66ae0ce10000000a11402f/frameset.htm
    [reward if helpful]
    regards,
    latika.

  • Non-HTTP(non-web) socket connection

    how do i setup non-HTTP(non-web) socket connection on my nokia 5235? please help...wanna whatsapp so badly

    Menu » Settings » Connectivity » Settings » Network destination » Internet
    Is that set correctly? Which network operator do you use? Because some operator in different countries with different settings, do not forget to mention your country, as well.

  • I cant imagine that this kind of issues we are facing with Apple the most respective smartphone company. it is the 2nd time i am writing to you with no reply. i bought my iphone 6 from dubai on March first the it stopped working on March 12th, i gave

    i cant imagine that we are facing this kind of issues with Apple, it is the 2nd time i am writing to you with no reply. i bought my iPhone 6 from Dubai on March first then it stopped working on March 12th, i gave it to you authorized re-seller here in Egypt and they replaced it in 24 days ... after another 6 days the new phone ALSO STOPPED working, i went back to them they said sorry we will replace it again.
    i really cant imagine that i paid more than US$850 2 months ago and until now i didn't use the mobile for more that 2 weeks.
    i really appreciate your help and response

    This is a user to user forum - you are not talking to Apple here, only to other users like yourself. You will need to take this up with Apple directly: http://www.apple.com/eg/support/contact/

  • Help with ports/sockets

    I am writing a program that accepts multiple users using sockets. It works well on my home network when i use the ip address 192.168.1.12. But when I try to get computers to connect outside of the network it doesnt work. Even when I change the ip address that the client is connecting to to the one i found at http://www.whatismyipaddress.com/
    which is 24.50.xxx.yy
    The port i'm using for the server and client is 11114.
    How do i make it work over the internet and not just my home network?

    A good place to start is:
    http://java.sun.com/j2se/1.4.1/docs/guide/rmi/socketfactory/SSLInfo.html
    There is a code example, but you will also need to follow the guide in the other link below to create the required key files.
    Don't base your knowledge of SSL RMI sockets solely on what I say here, as I'm fairly new to this so I may express myself wrong. But here is a 30,000 foot overview of what I did to get them to work:
    If you are using RSA on your SSL connection, a public and private key are required. For this to work, you must create a key (keystore) via Java's "keytool.exe" tool using the '-genkey' option (the keystore should eventually reside on your server). You will then create a certificate from that keystore using the '-export' option of the keytool. Lastly, you will import the certificate into your client's store of accepted certificates (the file java\lib\security\cacerts) via the '-import' option of keytool.
    For a full description, you need to read:
    http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html
    the section from this page on using keytool:
    http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html#CreateKeystore
    The example shows using a new custom file for the truststore, but I imported the certificate into Java's cacerts file instead. I was unable to find the certificate if it was not in this file, but I very well may have been doing something wrong.

  • Error in SXI_CACHE and reading HTTP destination: INTEGRATION_DIRECTORY_HMI

    I have been going over many posts etc trying to figure out why this quit working. Basically everything was working fine, and I did a Integration Process Scenario and uploaded that, once that was complete I started getting cache errors that where affecting everything else already configured in XI.
    I have tested in SM59 INTEGRATION_DIRECTORY_HMI and when I put in path
    /dir/hmi_cache_refresh_service/ext I get back a 200 response on connection test
    and put in path /dir/cacheRefresh I get a 500 response which I assume both are fine,
    I have also tested by the ping test in sicf using PIISUSER along with the url test of http://<host name>:<port>/dir/hmidiag/ext?method=info all was successful
    So the error seems to come when I run sxi_cache
    If I do a delta cache it comes up with the following error Prefix number: entry missing for system PIT client 300
    If I do a full cache refresh it runs in the background (and while it runs all the other scenario's work) but after the full cache comes back it has Unable to refresh cache contents with the message of Error when reading HTTP destination: INTEGRATION_DIRECTORY_HMI.
    Also once this error is checked all other scenerio's quite working again with the following message
    XIServer:UPDATE:Error when reading HTTP destination: INTEGRATION_DIRECTORY_HMI
    Does anyone have any ideas?
    I def award points
    Cheers
    Devlin

    Hi,
    I don't know if this is the exactly case we have here... but in our PI DEV and PRD environments it does not happen. In our QAS environment this error occurs everytime we create/change some integration scenario object and activate it. Then, all outbound interfaces start with this error. To solve it we go for a full refresh, delete Adapter Engine cache and restart ICM.
    We are trying for a long time to search why this happens only on QAS environment without success... But thanks good it does not happen in PRD
    regards.
    roberti

  • Performance problems with java sockets

    Hi ,
    I written a server class that simply writes the numbers and the client simply reads those numbers and prints them. When I run the both client and server on tha same machine there is no data loss found. But when I run the server on different machine than client I found heavy dataloss.(while theserver written numbers from 1-9000 the client is able read only 6000 plus). The data loss is increased when the data read from the server socket created by the VB application. Here with i am pasting the code snippet for the Server and the Client java files . Please help me in solving this problem.
    Client.java
    import java.net.*;
    import java.io.*;
    public class Client
         static Socket client = null;
         ObjectInputStream is = null;
         public Client() throws Exception
              client = new Socket("rajsekhar",3333);
              is = new ObjectInputStream (client.getInputStream());
              while(true){
                   Integer in = (Integer)is.readObject();
                   System.out.println(in.toString());
         public static void main(String[] args) throws Exception
              new Client();
    Server.java
    import java.net.*;
    import java.io.*;
    public class Server
         public static void main(String[] args) throws Exception
              ServerSocket server = null;
              server = new ServerSocket(3333);
              Socket s = server.accept();
              ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
              int i =1;
              while(true)
                   os.writeObject(new Integer(i));
                   System.out.println(i);
                   i++;
    please help me .
    thanks in advance,
    Sridhar Reddy .R

    Hi,
    Try putting os.flush() after doing the writting... I mean:
    os.writeObject(new Integer(i));
    os.flush();
    Good Luck!

Maybe you are looking for

  • IWeb no longer publishing

    My iWeb site http://web.mac.com/longhorn89/iWeb/Site/Library.html no longer works on either my home or work computers. OSX 10.4.11. iWeb 1.1.2. MobileMe is active. Please advise. Thanks in advance.

  • Importing user defined package in JDEV

    Hi, new to the JDEV9i tool. i have a project arranged in packages and am tryin to import this to the jdev9i. i successfully created the workspace and project and added all the packages. I can also view the package tree and package list but when i run

  • I just signed up for the FamilyBase program in order to control/manage my childrens' usage

    I just signed up for the FamilyBase program in order to control/manage my childrens' usage.  I love the idea of the 'watchlist' function (which notifies me if there is any text/call activity with phone nums I've flagged); however, I don't like that m

  • Pages won't let me move my document out of the cloud

    The instructions for moving a Pages document out of the cloud is to go to the menue at the top of the screen, choose.   "File>Move to".  BUT...  Move To is not a highlighted option.  I cannot choose it.  What is wrong?

  • ITunes shuts down my PC while burning and/or importing.

    Ok so a couple of weeks ago I noticed iTunes was shutting my computer down while I was importing a CD (tried it 3 times). I thought maybe it was because I only had about 325MB of space left on my HD. Tonight I noticed that iTunes is shutting down my