我已经多次搜索过这个问题,几乎所有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
。
答案 0 :(得分:0)
这是我的代码,它的工作正常,试试吧:
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");
}
?>