Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    forums

Go Back   Code Forums > Application and Web Development > Java

Reply
 
LinkBack Thread Tools Display Modes
Old 03-06-2005, 05:44 PM   #1 (permalink)
wishknew
Wisnu Widiarta
 
wishknew's Avatar
 
Join Date: Feb 2005
Location: Indonesia
Posts: 14
wishknew is on a distinguished road
Send a message via Yahoo to wishknew
Error java.net.ProtocolException: Cannot write output after reading input.

Hello guys,

I've got stuck with making a post connection using https.
Here is my code:

HTTPS Client
Code:
public void run() {
        HttpsURLConnection httpsConnection = null;
        int responseCode=0;
        String address = "https://" + config.getHTTPSServerAddress();
        SSLContext sc = null;
        String encodedContent;

        prepareSecureConnection(sc);

        httpsConnection = openConnection(address, httpsConnection, responseCode);
        printResponseContent(httpsConnection);
        httpsConnection.disconnect();

        encodedContent = getEncodedContent();
        writeEncodedContent(httpsConnection, encodedContent);//error here
    }

    private void writeEncodedContent(HttpsURLConnection httpsConnection, String encodedContent) {
        OutputStreamWriter writer;
        try {
             outputStream = httpsConnection.getOutputStream();
             writer = new OutputStreamWriter(outputStream);
             writer.write(encodedContent);
             writer.flush();
             outputStream.close();

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getEncodedContent() {
        String content = "";
        int data;
        try {
            inputStream = clientIFX.getInputStream();
            data = inputStream.read();
            while (data != -1) {
                content += (char)data;
                data = inputStream.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (content.equals("")) {
            return "";
        }
        else {
            return Base64.encodeBytes(content.getBytes(), Base64.GZIP);
        }
    }

    private void printResponseContent(HttpsURLConnection connection) {
        StringBuffer buffer;
        InputStream input;
        BufferedReader dataInput;
        String line;
        String responseContent = "";
        try {
            buffer = new StringBuffer();
            input = connection.getInputStream();
            dataInput = new BufferedReader(new InputStreamReader(input));
            while ((line = dataInput.readLine()) != null) {
                buffer.append(line);
                buffer.append('\n');
            }
            input.close();
            responseContent = (String) buffer.toString().trim();
        } catch (Exception e) {
            System.err.println(e);
        }
        System.out.println(responseContent);

    }

    private HttpsURLConnection openConnection(String address, HttpsURLConnection connection, int responseCode) {
        URL url;
        try {
            url = new URL(address);
            connection = (HttpsURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);

            responseCode = connection.getResponseCode();

        } catch (Exception e) {
            System.err.println("Ooops : " + e + " (Response code is " + responseCode + ")");
        }
        return connection;
    }

    private void prepareSecureConnection(SSLContext sc) {
        try {
            sc = SSLContext.getInstance("SSLv3");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        TrustManager[] tma = {this};
        try {
            sc.init(null, tma, null);
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        SSLSocketFactory ssf = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(ssf);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
The error was:
java.net.ProtocolException: Cannot write output after reading input.
at sun.net.www.protocol.http.HttpURLConnection.getOut putStream(HttpURLConnection.java:565)
at sun.net.www.protocol.https.HttpsURLConnectionImpl. getOutputStream(DashoA12275)
at IFXCompressor.writeEncodedContent(IFXCompressor.ja va:55)
at IFXCompressor.run(IFXCompressor.java:49)


My question is how to post a message using HttpsURLConnection? (without doing any get at all)

Thank you,


WishKnew
wishknew is offline   Reply With Quote
Old 03-06-2005, 08:34 PM   #2 (permalink)
wishknew
Wisnu Widiarta
 
wishknew's Avatar
 
Join Date: Feb 2005
Location: Indonesia
Posts: 14
wishknew is on a distinguished road
Send a message via Yahoo to wishknew
Another problem

After changing the writeEncodedContent method, I can get rid the error off from my program.

The changes are:
Code:
private void writeEncodedContent(String encodedContent) {
        DataOutputStream writer;
        HttpsURLConnection connection = null;
        encodedContent = "content=" + encodedContent;

        try {
            connection = (HttpsURLConnection) new URL("https://10.8.8.40").openConnection();
            connection.setRequestProperty("User-Agent", "IFXClient");
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "text/plain");
            connection.setRequestProperty("Content-Length", "" + encodedContent.length());

            connection.connect();

        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
             writer = new DataOutputStream(connection.getOutputStream());
             writer.writeBytes(encodedContent);
             writer.flush();
             writer.close();

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
And the server code for handling the request is :

Code:
public ProcessConnection(Socket s) { // constructor
      client = s;
      try {
         is = new BufferedReader(new InputStreamReader
           (client.getInputStream()));
         os = new DataOutputStream(client.getOutputStream());
      } catch (IOException e) {
         System.out.println("Exception: "+e.getMessage());
      }

      System.out.println("Processing connection from " + s.getInetAddress().toString());

      this.start(); // Thread starts here...this start() will call run()
   }

   public void run() {
      try {
         // get a request and parse it.
            
         String request = is.readLine();
         System.out.println( "Request: "+request );
       } catch (Exception e) {
         System.out.println("Exception: " +
           e.getMessage());
      } 
   }
The error is gone, but the request become NULL when I try to post. I don't have any problem for GET message.

Please advice.

Thank you in advance.

Wisnu (WishKnew)
wishknew is offline   Reply With Quote
Old 03-07-2005, 06:35 AM   #3 (permalink)
Belisarius
Java fanboy
 
Belisarius's Avatar
 
Join Date: Aug 2003
Posts: 1,149
Belisarius is on a distinguished road
What does the output usually look like for a GET?
__________________
GitS
Belisarius is offline   Reply With Quote
Old 03-07-2005, 03:56 PM   #4 (permalink)
wishknew
Wisnu Widiarta
 
wishknew's Avatar
 
Join Date: Feb 2005
Location: Indonesia
Posts: 14
wishknew is on a distinguished road
Send a message via Yahoo to wishknew
Quote:
What does the output usually look like for a GET?
Actually, I just open its connection (default to index.html), get the InputStream, and read from it. I've got full HTML code from the server.

Code:
private void printResponseContent(HttpsURLConnection connection) {
        StringBuffer buffer;
        InputStream input;
        BufferedReader dataInput;
        String line;
        String responseContent = "";
        try {
            buffer = new StringBuffer();
            input = connection.getInputStream();
            dataInput = new BufferedReader(new InputStreamReader(input));
            while ((line = dataInput.readLine()) != null) {
                buffer.append(line);
                buffer.append('\n');
            }
            input.close();
            responseContent = (String) buffer.toString().trim();
        } catch (Exception e) {
            System.err.println(e);
        }
        System.out.println(responseContent);
    }
I have copy the information from http://www.dcs.shef.ac.uk/~fabio/COM...web%20MINI.pdf
and http://www.javaworld.com/javaworld/j...323-traps.html as basic of my code.

I will be glad if one of you can give me a simple httpSServer class which print any request and a httpClient (which connect to httpsUrlConnection) and doing a simple POST.

Thank you,


WishKnew
wishknew is offline   Reply With Quote
Old 03-07-2005, 04:01 PM   #5 (permalink)
sde
Moderator
 
sde's Avatar
 
Join Date: May 2002
Location: us.ca
Posts: 4,471
sde is on a distinguished road
here is some code i use to consume a web service using GET, but not post. sorry it's not much help. good luck.
Code:
URL productURLRequest;
BufferedReader in;
String productURLResponse;
  
// read url
productURLRequest = new URL("http://www.myserver.com/lookup.php?ProdID=someproduct");
in = new BufferedReader(new InputStreamReader(productURLRequest.openStream()));

if((productURLResponse = in.readLine()) == null)
  productURLResponse = "0";

in.close();
__________________
Mike
sde is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Adjust physical output size dynamically metazai PHP 8 08-24-2004 10:15 AM
hashing help saiz66 Standard C, C++ 2 06-28-2004 01:39 AM
Compiler Error saiz66 Standard C, C++ 9 06-10-2004 06:44 PM
reading a web form for input variables sde PHP 3 08-12-2003 10:02 AM
dynamic allocation..urgent help needed!!! kashif Standard C, C++ 4 04-21-2003 08:50 AM


All times are GMT -8. The time now is 09:34 PM.


Powered by vBulletin® Version 3.7.0
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.0.0 RC8





Copyright © 2000-2008, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting