0

这是我通过 HTTPPost 请求发送数据的 java 代码:

import java.io.*;
import java.net.*;
class HttpURLConnectionEx{
    public static void main(String[] args) throws Exception{    
    URL targetURL = new URL("http://localhost/JAVA/post.php");
    HttpURLConnection conn =(HttpURLConnection) targetURL.openConnection();
    String body= "fName="+ URLEncoder.encode("value1","UTF-8")+"&lName=" + URLEncoder.encode("value2","UTF-8");
    conn.setDoOutput(true);
    conn.setInstanceFollowRedirects(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("charset", "UTF-8");
    conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
    try
    {
     OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
     out.write(body);

      // Get the response
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while((line = rd.readLine()) != null) {
           System.out.println(line);
      }
      }catch(Exception e){
        e.printStackTrace();
      } 
   }
}

这是我在 localhost 中的 PHP 代码:

<?php
    $data = $_POST["fName"];
    $dbc = mysqli_connect('localhost','root','root123','JAVA')
           or die("error connecting to mysql server");
    $query = "INSERT INTO insert_table(data) VALUES('".$data."')";
    if($query){
        echo "data inserted sucessfully";
    }
    $result = mysqli_query($dbc,$query) or die("error querying database");
?>

这是我在命令行中运行它时得到的输出: 在此处输入图像描述

4

1 回答 1

0

flush后面的Awrite是必需的。

 out.flush();

编辑

未定义索引:fName

php错误很清楚,不是吗?该$_POST数组不包含您的 POST 变量。

首先,我在 php 端检查了帖子的内容,var_dump($_POST)并且:

/* save the raw post to a file */
file_put_contents('/tmp/post.txt', file_get_contents('php://input'));

两者都是空的,所以我使用了wireshark来检查 HTTP/POST 内容,它完成了,但是有Content-Length: 0和没有body.

很少有谷歌搜索类似于您的代码的内容,我注意到该flush平均值OutputStreamWriter已被缓冲,并且在发布请求时,输出可能无法写入(发送到服务器)或仅部分写入,这是零内容长度的一个很好的理由。

此时我认为您不需要使用conn.setRequestPropertyfor "Content-Length",它应该根据您的缓冲区内容长度进行更新。

于 2013-09-29T07:37:37.640 回答