有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用HTTPPost请求从java代码向localhost中的PHP发送数据时出错

这是我通过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");
?>

这是我在命令行中运行它时得到的输出: enter image description here


共 (0) 个答案