PHP没有接收到来自java的POST请求


PHP not receiving POST requests from java

我已经在谷歌上搜索了很多次了,并且几乎完成了这个问题的所有Q和A。然而,我似乎仍然无法正确地向PHP发送POST请求。我目前使用的代码是:

public static void main(String[] args){
          Map<String, String> m = new HashMap<String, String>();
          m.put("key", generateCode());
          try {
            logData("http://example.com/data", m);
        } catch (Exception e) {
            System.out.println("There was an error");
        }
      }
      public static void logData(String url, Map<String, String> data) throws Exception {
            URL siteUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            Set keys = data.keySet();
            Iterator keyIter = keys.iterator();
            String content = "";
            for(int i=0; keyIter.hasNext(); i++) {
                Object key = keyIter.next();
                if(i!=0) {
                    content += "&";
                }
                content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
            }
            System.out.println(content);
            out.writeBytes(content);
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            while((line=in.readLine())!=null) {
                System.out.println(line);
            }
            in.close();
        }

发送帖子请求,我的PHP是:

<?php
echo $_POST['key'];

我总是返回错误Notice: Undefined index: key in /var/www/html/data/index.php on line 2

这是我的代码,它工作正常,试试看:

java代码:

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class JavaPhpTest
{
    public static void main(String[] hex)
    {
    try{
    URL url = new URL("http://sandstorm.xzn.ir//hex.php");
    URLConnection uc = url.openConnection();
    HttpURLConnection huc = (HttpURLConnection)uc;
    String un = "un=hamid&pass=123456";
    byte[] data = un.getBytes(StandardCharsets.UTF_8);
    huc.setRequestMethod("POST");
    huc.setDoInput(true);
    huc.setDoOutput(true);
    DataOutputStream osw = new DataOutputStream(huc.getOutputStream());
    osw.write(data);
    osw.close();
    InputStreamReader isr = new InputStreamReader(huc.getInputStream());
    Scanner sc = new Scanner(isr).useDelimiter("''A");
    System.out.println(sc.next());
    isr.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

php代码(在服务器上):

<?php
$username = $_POST["un"];
$password = $_POST["pass"];
if($username == "hamid" && $password == "123456"){
    echo("you are right");
}else{
    echo("something is wrong");
}
?>