在Java中发送HTTP POST请求并在PHP中接受POST请求

3
我需要做的是通过HTTP POST请求向php脚本发送用户名和密码,以便查询正确信息的数据库。目前我在发送POST请求和接收数据方面遇到了困难。
为了发送用户名和密码,我正在使用以下内容:
public class post {
    public static void main(String[] args) throws ClientProtocolException, IOException {
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("http://www.example.com/practice.php");

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        params.add(new BasicNameValuePair("username", "user"));
        params.add(new BasicNameValuePair("password", "hunter2"));
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        //Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
                // do something useful
            } finally {
                instream.close();
            }
        }

    }
}

我正在使用的PHP脚本用于收集信息,如下所示,它很简单,但目前仅用于测试。

<?php
$username = $_POST['username'];
$password = $_POST['password'];
echo "username = $username<br>";
echo "password = $password<br>";
 ?>

我想知道有没有人能帮我指明正确的方向,让我能在php中接受来自Java的HTTP POST请求,或者告诉我是否正确地发送了POST请求,非常感谢任何帮助。


使用Json怎么样? - Panda
关于使用Java发送POST请求的内容 https://dev59.com/hW855IYBdhLWcg3wrGZY - RubioRic
我认为你的实际PHP代码中不需要其他任何东西,只需在可从Java代码访问的服务器上执行即可。 - RubioRic
@M.S.P 你说的JSON是什么意思?我知道它是什么,但它如何帮助我呢? - terrabl
请给我几分钟时间。我会在我的回答中详细说明。 - Panda
@RubiaRic,你所说的从Java代码可访问的服务器是什么意思? - terrabl
1个回答

3
现在,在进行此操作时,我建议您记住以下几点。
  1. Try Making use of JSON: Json stands for JavaScript Object Notation. Itis a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write.

    public static void main(String[] args){
    JSONObject obj = new JSONObject();
    
    obj.put("username", username);
    obj.put("password", password);
    System.out.print(obj);
    // And then, send this via POST Method.
    }
    }
    

    For Php part,

    ...
    $data = file_get_contents("php://input");
    $json = json_decode($data);
    $username = $json['username'];
    $password = $json['password'];
    ...
    
这里有一个很好的参考资料,关于Json
  1. Make Use of Sessions When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

    <?php
    $_SESSION["user"] = "green";
    echo "Session variables are set.";
    // Now store this in your database in a separate table and set its expiry date and time.
    ?>
    

    Here is a reference to that as well sessions.

  2. Use SSL : Secure Socket Layer (SSL) technology is security that is implemented at the transport layer.SSL allows web browsers and web servers to communicate over a secure connection. In this secure connection, the data that is being sent is encrypted before being sent and then is decrypted upon receipt and before processing. Both the browser and the server encrypt all traffic before sending any data. SSL addresses the following important security considerations.

a. 身份验证:在您首次尝试通过安全连接与Web服务器通信时,该服务器将向您的Web浏览器提供一组凭据,即服务器证书。证书的目的是验证该站点是其所声称的人和事物。在某些情况下,服务器可能会请求客户端证书以验证客户端的身份(这称为客户端身份验证)。

b. 机密性:当数据在网络上在客户端和服务器之间传递时,第三方可以查看和拦截此数据。 SSL响应被加密,因此第三方无法解密数据,数据保持机密。

c. 完整性:当数据在网络上在客户端和服务器之间传递时,第三方可以查看和拦截此数据。 SSL有助于确保第三方不会在传输过程中修改数据。

此外,以下是一些参考资料。 SSL建立文档使用Java进行SSL


发送JSON是否类似于我在上面的代码中发送POST请求,或者我应该如何将JSON POST到我的php脚本中。另外,$data = file_get_contents("php://input");是什么意思?@M.S.P - terrabl
php://inputжҳҜдҪ зӯ”жЎҲзҡ„е…ій”®гҖӮhttp://php.net/manual/en/wrappers.php.php - Panda
我刚刚提出了另一种通过Json实现的方法。因为Json是API通信的主要方式之一,所以如果您计划部署一个服务,许多人认为JSON是最好的选择。您也可以使用XML来实现相同的功能。 - Panda
我不太清楚自己卡在哪里了,只是在整个服务器端的事情上遇到了麻烦,比如发送POST请求,然后让服务器端的PHP接受它们。 - terrabl
我建议你在另一个问题中发布你的方法,特别是强调你想要做什么!同时也要指明你遇到的错误。对于这个问题,还有其他不清楚的地方吗? - Panda
不是的,我只是接受了你的答案,我会尽快发布另一个问题。 - terrabl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接