How can I call a php script from java code?

As the title says ... I tried using the following code to execute a PHP script when a user clicks a button in a Java Swing application:

URL url = new URL( "http://www.mywebsite.com/my_script.php" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();

But nothing happens ... Is something wrong?

+3
source share
2 answers

I think you are missing the next step, which looks something like this:

InputStream is = conn.getInputStream();

HttpURLConnectionbasically only opens the socket on connectto do something that you need to do something like a call getInputStream()or even bettergetResponseCode()

URL url = new URL( "http://google.com/" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
    InputStream is = conn.getInputStream();
    // do something with the data here
}else{
    InputStream err = conn.getErrorStream();
    // err may have useful information.. but could be null see javadocs for more information
}
+5
source
final URL url = new URL("http://domain.com/script.php");
final InputStream inputStream = new InputStreamReader(url);
final BufferedReader reader = new BufferedReader(inputStream).openStream();

String line, response = "";

while ((line = reader.readLine()) != null)
{
    response = response + "\r" + line;
}

reader.close();

"" . , ( , \n,\r ).

, .

+1

Source: https://habr.com/ru/post/1771490/


All Articles