1

I am trying to create a Simplest WebServer and Client using HTTP. I should use a tunnel way that uses two connections at the same time; one is a GET connection to recieve data and the other is a POST connection to send data back.

Below is my code:

//client GET Request
setoURL(new URL("http://" + input.getIp() + ":" + input.getPort() + input.getUrlPath()));
conn = (HttpURLConnection) getoURL().openConnection();
            
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.addRequestProperty("User-Agent", "VVTK (ver=40)");
conn.addRequestProperty("Accept", "application/x-vvtk-tunnelled");
conn.addRequestProperty("x-sessioncookie", uniqueId());
conn.addRequestProperty("Pragma", "no-cache");
conn.addRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Authorization",/*The Authorization*/);
conn.getResponseCode();

//Client POST request
HttpURLConnection second2 = (HttpURLConnection) apiCommand.getoURL().openConnection();
second2.setRequestMethod("POST");
second2.setReadTimeout(5000);
second2.setRequestProperty("User-Agent", "VVTK (ver=40)");
second2.setRequestProperty("x-sessioncookie", xsession);
second2.setRequestProperty("Pragma", "no-cache");
second2.setRequestProperty("Cache-Control", "no-cache");
second2.setRequestProperty("Content-Length", "7");
second2.setRequestProperty("Expires", "Sun, 9 Jan 1972 00:00:00 GMT");
second2.setRequestProperty("VerifyPassProxy", "yes");
second2.setRequestProperty("Authorization", /*The Authorization*/);
second2.setDoOutput(true);
reqStream = new DataOutputStream(second2.getOutputStream());
reqStream.writeBytes("Q2FuU2Vl");
reqStream.flush();

in = new BufferedReader(new InputStreamReader(second.getInputStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
}

The problem is the post request not sent. The first connection ((GET Request)) will send me the events or all responses. I should never disconnect or get data from the second connection (POST request).

Question

Why is the POST request not send?

Community
  • 1
  • 1
Sidaoui Majdi
  • 399
  • 7
  • 26
  • check the example http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/ – Biswajit Dec 09 '13 at 11:21
  • both get and post to same URL? what is the service type? GET or POST? – dev2d Dec 09 '13 at 11:38
  • Thanks for replying, i have seen this example and it doesen't work for me, allways the POST Request send only when i do this `second2.getResponseCode();` or this `BufferedReader inpost = new BufferedReader(new InputStreamReader(second2.getInputStream()));` – Sidaoui Majdi Dec 09 '13 at 11:42
  • @VD, yes both get and post to same URL, the service type is GET and POST – Sidaoui Majdi Dec 09 '13 at 11:43

1 Answers1

2

after

reqStream.writeBytes("Q2FuU2Vl");
reqStream.flush();

add this line

reqStream.close();

View code below. I send, from java, parameters via GET or POST and files via POST, to php. In the same time, data will send via both methods, POST and GET. Java code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package httpcommunication;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 *
 * @author me0x847206
 */
final public class HTTPCommunication {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        HTTPCommunication http = new HTTPCommunication("http://localhost/post/index.php");

        http.addParam("data0", "0");
        http.addParam("1");
        http.addParam("", "2");
        http.addFile( "", "txtFile.txt");
        http.addFile( "", "photo2");
        http.addFile( "photo3", "photo.png");

        http.viaGET();
        System.out.println("text = " + http.getLastResponse() );
    }

    HTTPCommunication(String url) {
        this.url = url;

        setFilePrefix("f_");
        setParamPrefix("p_");
        setEncoding("ISO-8859-1");

        defaultFileName = 0;
        defaultParamName = 0;

        params = new java.util.TreeMap<>();
        headers = new java.util.TreeMap<>();
        files = new java.util.TreeMap<>();
    }

    public void viaPOST() {
       send(POST_METHOD);
    }

    public void viaGET() {
        send(GET_METHOD);
    }

    public void setURL(String s) {
        url = s;
    }

    public boolean setEncoding(String s) {
        if(!java.nio.charset.Charset.isSupported( s ))
            return false;
        urlEncoding = s;
        return true;
    }

    public boolean setParamPrefix(String s) {
        if( "".equals( s ) )
            return false;
        paramPrefix = s;
        return true;
    }

    public boolean setFilePrefix(String s) {
        if( "".equals( s ) )
            return false;
        filePrefix = s;
        return true;
    }

    public String getURL() {
        return url;
    }

    public String getEncoding() {
        return urlEncoding;
    }

    public String getParamPrefix() {
        return paramPrefix;
    }

    public String getFilePrefix() {
        return filePrefix;
    }

    public String getLastResponse() {
        return lastResponse.toString();
    }

    public int getLastResponseCode() {
        return lastResponseCode;
    }

    public void addHeader(String key, String value) {
        if("".equals( key ))
            return;
        if(headers.containsKey( key )) {
            headers.remove( key );
        }
        headers.put( key, value);
    }

    public void addParam(String value) {
        addParam("", value);
    }

    public void addParam(String key, String value) {
        key = paramPrefix + ("".equals( key ) ? ("" + ++defaultParamName) : key);
        if(params.containsKey( key )) {
            params.remove( key );
        }
        params.put( key, value);
    }

    public void addFile(String path) {
        addFile("", path);
    }

    public void addFile(String name, String path) {
        name = filePrefix + ("".equals( name ) ? ("" + ++defaultFileName) : name);
        if(files.containsKey( name )) {
            files.remove( name );
        }
        files.put( name, path); 
    }

    public void reset() {
        headers.clear();
        params.clear();
        files.clear();
        defaultParamName = 0;
        defaultFileName = 0;
    }

    private void send(int type) {
        try {
            if( url.startsWith("https") )
                return;

            StringBuffer urlParams = new StringBuffer();

            for(String s : params.keySet()) {
                urlParams.
                        append("&").
                        append(URLEncoder.encode( s, urlEncoding)).
                        append("=").
                        append(URLEncoder.encode(params.get( s ) , urlEncoding));
            }

            System.out.println( urlParams + "" );

            URL object = new URL(
                    url + (POST_METHOD == type ? "" : ("?" + urlParams))
            );

            HttpURLConnection connection = (HttpURLConnection) object.openConnection();

            /*
                with that line or without, is same effect
            */
            //connection.setRequestMethod( POST_METHOD == type ? "POST" : "GET");

            connection.setDoOutput( true );
            connection.setDoInput( true );
            connection.setUseCaches( false );
            connection.connect();

            for(String s : headers.keySet()) {
                connection.setRequestProperty( s, headers.get( s ) );
            }

            try (DataOutputStream out = new DataOutputStream( connection.getOutputStream() )) {
                if( POST_METHOD == type ) {
                    out.writeBytes( urlParams.toString() );
                }

                for(String name : files.keySet()) {
                    out.writeBytes( "&" + URLEncoder.encode( name, urlEncoding) + "=");
                    writeFile( out, files.get( name ) );
                }

                out.flush();

                lastResponseCode = connection.getResponseCode();

                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    lastResponse = new StringBuffer();
                    while( null != (line = in.readLine()) ) {
                        lastResponse.append( line );
                    }
                }
            }
            connection.disconnect();
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }

    private void writeFile(final DataOutputStream out, final String path) {
        try {
            try (FileInputStream in = new FileInputStream(path)) {
                byte bytes[] = new byte[4096];
                int read, totalRead = 0;
                while( -1 != (read = in.read(bytes)) ) {
                    out.writeBytes( URLEncoder.encode( new String( bytes, 0, read, urlEncoding ), urlEncoding) );
                    totalRead += read;
                }
                System.out.println("totalRead from " + path + " = " + totalRead + " (bytes).");
            }
        } catch (Exception e) {
            System.out.println("Exception 2");
        }
    }

    public static final int POST_METHOD = 0;
    public static final int GET_METHOD = 1;

    private String paramPrefix;
    private String filePrefix;

    private int defaultFileName, defaultParamName;

    private final java.util.SortedMap<String, String> params;
    private final java.util.SortedMap<String, String> headers;
    private final java.util.SortedMap<String, String> files;

    private String url = "";
    private String urlEncoding;
    private StringBuffer lastResponse = new StringBuffer();
    private int lastResponseCode = 0;
}

php code:

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
            foreach($_POST as $key => $value) {
                echo "<br \>\$_POST['$key'] ";
                if( "f_" == substr( $key, 0, 2) ) {
                    echo " <= this is a file";
                    $file = fopen( $key, "wb");
                    fwrite( $file, $value );
                    fclose( $file );
                } else {
                    echo " = $value";
                }
            }
            foreach($_GET as $key => $value) {
                echo "<br \>\$_GET['$key'] = $value";
            }
        ?>
    </body>
</html>

Java output:

run:
&p_1=1&p_2=2&p_data0=0
totalRead from txtFile.txt = 3961 (bytes).
totalRead from photo2 = 17990 (bytes).
totalRead from photo.png = 56590 (bytes).
text = <!DOCTYPE html><!--To change this license header, choose License Headers in Project Properties.To change this template file, choose Tools | Templatesand open the template in the editor.--><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <br \>$_POST['f_1']  <= this is a file<br \>$_POST['f_2']  <= this is a file<br \>$_POST['f_photo3']  <= this is a file<br \>$_GET['p_1'] = 1<br \>$_GET['p_2'] = 2<br \>$_GET['p_data0'] = 0    </body></html>
BUILD SUCCESSFUL (total time: 1 second)

Data writed to conn.getOutputStream() must respect that format: [&]paramName=paramValue[&paramName=paramValue] and so on, where paramName and paramValue must be encoded with URLEncoder.encode( paramName, encodedFormat); In your code, data writting is an String that no respect that format, so php does not understand what is this, name or value? and ignore this

Teodor
  • 114
  • 7
  • Please specify your ansewr – Lal krishnan S L Apr 21 '14 at 13:44
  • 1
    Can you please explain this code (in your answer)? You might get more upvotes that way! The original question is "Why is the POST request not send?" This may fix the problem, but it does not answer the question. If you explain what this code does, _that_ will answer the question. – The Guy with The Hat Apr 21 '14 at 14:35