Hello guys... I'm trying to develop an application with a GUI that sends and receives data via http, by sending a url via POST and eading the content generated by the url.

or instance, if i send a nick and order number, the server generates a SessionID via html.

My current code is the following:

import java.awt.TextField;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ContentHandlerFactory;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import sun.net.www.protocol.http.HttpURLConnection;

/**
 *
 * @author Programador
 */
public class UIMensaje extends javax.swing.JFrame {

    private java.util.Map<String,java.util.List<String>> responseHeader = null;
    private java.net.URL responseURL = null;
    private int responseCode = -1;
    private String MIMEtype  = null;
    private String charset   = null;
    private Object content   = null;

    /**Contador de caracteres máximos en un mensaje, y controlador del texto
     * del mensaje.
     * 
     * @param field Campo de texto de cadena del mensaje
     * @param contador Campo de texto de contador de caracteres
     * @param max Cantidad máxima de caracteres en el mensaje
     */
    public void textCounter(TextField field, TextField contador, int max)
    {
        
        if (field.getText().length()>max)
        {
            field.setText(field.getText().substring(0,max));
        }
        else
        {
            contador.setText(String.valueOf(max-field.getText().length()));
        }
        
    }

    private Object readStream( int length, java.io.InputStream stream )
        throws java.io.IOException {
        final int buflen = Math.max( 1024, Math.max( length, stream.available() ) );
        byte[] buf   = new byte[buflen];
        byte[] bytes = null;

        for ( int nRead = stream.read(buf); nRead != -1; nRead = stream.read(buf) ) {
            if ( bytes == null ) {
                bytes = buf;
                buf   = new byte[buflen];
                continue;
            }
            final byte[] newBytes = new byte[ bytes.length + nRead ];
            System.arraycopy( bytes, 0, newBytes, 0, bytes.length );
            System.arraycopy( buf, 0, newBytes, bytes.length, nRead );
            bytes = newBytes;
        }

        if ( charset == null )
            return bytes;
        try {
            return new String( bytes, charset );
        }
        catch ( java.io.UnsupportedEncodingException e ) { }
        return bytes;
    }
    
    /** Primero, se obtiene el numero de sesion para el envío de mensajes. Luego,
     *  Usando el número, se mantiene abierta una sesión de mensajería.
     * 
     * @param sender Nombre de la persona que envía el mensaje
     * @param to Número del destinatario del mensaje
     * @param txt Contenido del mensaje
     */
    public void sendTxt(String sender, String to, String txt, JLabel sesion)
    {
        
        try 
        {
            
            //Construir datos
            String orden = "1"; //Número de orden para el servidor
            String pin = "undefined"; //Número de pin para el usuario, "undefined" por defecto
            String dstphone = "504" + to; //Número de teléfono del destinatario
            
            String txtmsg = URLEncoder.encode(txt, "UTF-8"); //Codificar mensaje de texto
            String nick = URLEncoder.encode(sender, "UTF-8"); //Codificar nombre de emisor
            
            String dataOrd1;
            
            dataOrd1 = "orden=" + orden + "&nick=" + nick;
            
            //Enviar primera solicitud, para generar el número de sesión
            URL url = new URL("http://interactivo.mensajito.com/interactivo555/client.php");
            URLConnection uconn = url.openConnection();
            uconn.setDoOutput(true);
            uconn.setDoInput(true);
            HttpURLConnection conn = (HttpURLConnection)uconn;
            
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(dataOrd1);
            wr.flush();
            
            //Obtener respuesta de primera solicitur y obtener el número de sesión
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            //leer lineas de respuesta y procesarlas
            String resp = "", linea;
            
            while ((linea = rd.readLine()) != null)
            {

                resp += linea;

            }

            sesion.setText(conn.getContent().toString());


            /*// Get the response.
            responseHeader = conn.getHeaderFields( );
            responseCode = conn.getResponseCode();
            responseURL = conn.getURL( );
            final int length  = conn.getContentLength( );
            final String type = conn.getContentType( );
            if ( type != null ) {
                final String[] parts = type.split( ";" );
                MIMEtype = parts[0].trim( );
                for ( int i = 1; i < parts.length && charset == null; i++ ) {
                    final String t  = parts[i].trim( );
                    final int index = t.toLowerCase( ).indexOf( "charset=" );
                    if ( index != -1 )
                        charset = t.substring( index+8 );
                }
            }

            // Get the content.
            final java.io.InputStream stream = conn.getErrorStream( );
            if ( stream != null )
                content = readStream( length, stream );
            else if ( (content = conn.getContent( )) != null &&
                content instanceof java.io.InputStream )
                content = readStream( length, (java.io.InputStream)content );
            conn.disconnect( );*/


            //sesion.setText((String)content);
            
        } 
        catch (Exception e) 
        {
            sesion.setText("Error al obtener numero de sesion");
        }
        
         
    }

    private void enviarActionPerformed(java.awt.event.ActionEvent evt) {

        sendTxt(de.getText(), para.getText(), mensaje.getText(), sesion);

    }

I know the solution is as simple as reading the correct value, but I don't know what value I have to read.

The string i'm trying to read from the url can be seen in this example.

Thank you

Are you saying that you don't know how to parse the value you are getting? Or that you aren't able to capture the response at all?

I'm not able to capture the response (apparently), because when i read the InputStream (stored in a BufferedReader rd ), the text in my output JLabel is "" , so i guess i'm doing it wrong.

Did you try the link i posted?

Have you tried adding "client.php?" to the string you're sending? I used the following code fragment and pulled back the id just fine

try {
            // Create a URL for the desired page
            URL url = new URL("http://interactivo.mensajito.com/interactivo555/client.php?orden=1&nick=Niche");

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                // str is one line of text; readLine() strips the newline character(s)
                System.out.println(str);
                Matcher m = Pattern.compile("session=(\\d+)").matcher(str);
                if (m.matches()){
                    System.out.println(">> captured id: "+m.group(1));
                }
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }

I haven't been able to get it to respond to POST requests. Are you certain that the php page is written to use them? It might only be coded for GET requests like the link you posted.

That did not quite solve it, but i stopped using a URLConnection, and just used a url.openStream(), and that didi it... thank you very much!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.