开发者

php server - java client - post and echo

i'm completely new to java, php and so on ... so please forgive my stupid question.

I want to write a PHP server application which receives a name from a Java client application. It should respond printing the name on the output and sending a status message (Write failed/success).

How would I get the Java client send the name and receive the reply from the PHP program, and how would the PHP program receive and print the name and send the reply? I have googled a lot: i have found several code examples but the script doesn't work still.

Trying to make it work i've written the following:

Server Side

    <html>
        <head>
            <title>PHP Giulio</title>
        </head>
        <body>   
            <?php
$username = "Giulio";                
echo "$username"; 
$username = $_POST['username'];
print "$username"; 
            ?>
        </body>
    </html>

in this way i thought that before the server had received the name from the client "Giulio" was printed, while, after having received it, the received name would have been printed.

On the other side

Client Side

import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.*;

public class JavaPHP {
    public static void main(String[] args){
        URL url;
        try {
            url = new URL("http://www.mydomain.com/myfile.php");
            URLConnection connection 开发者_JS百科= url.openConnection(); 
            connection.setDoOutput(true); 
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write("username=NameToBeWritten");
            out.flush(); 
            out.close(); 
            InputStream in=connection.getInputStream();
            in.read();
            in.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }
}

well ... i obtain that on the output i see only the name Giulio. How can i make it receive and print the sent name?

Please help me

Thanks in advance.

Giulio!!


URL Parameters require a question mark character to successfully interpret your requests.

try to replace

out.write("username=NameToBeWritten");

with

out.write("?username=NameToBeWritten");

And see if that solves the problem, also you might want to add a sleep before opening the input stream since you are immediately opening the input stream to receive the data, and the server might not be done flushing the output to your client side ode... just a thought.

I know the question is old, but let us know if you had any success.


You need to set the request method to POST from Java. You can do this by casting connection to an HttpURLConnection and call setRequestMethod("POST") on it:

HttpURLConnection urlCon = (HttpURLConnection) connection;
urlCon.setRequestMethod("POST");

Add it before you call setDoOutput.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜