2012-01-15 126 views
0

我正在尝试将POST数据从java发送到PHP页面。但它不起作用。无论我在PHP页面中回应的工作正常,但是当我发送数据时,它给出 - '未定义索引' 可能是什么问题? 这是我的java文件。用java发送数据到php页面

import java.net.*; 
import java.io.*; 

class Main { 
public static void main(String args[]) throws IOException { 

    URL url = new URL("http://localhost/CD/user/test"); 
    String result = ""; 
    String data = "fName=" + URLEncoder.encode("Atli", "UTF-8"); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    try { 

     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setUseCaches(false); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded"); 

     // Send the POST data 
     DataOutputStream dataOut = new DataOutputStream(
       connection.getOutputStream()); 
     dataOut.writeBytes(data); 
     dataOut.flush(); 
     dataOut.close(); 

     BufferedReader in = new BufferedReader(new InputStreamReader(
       url.openStream())); 

     String g; 
     while ((g = in.readLine()) != null) { 
      result += g; 
     } 
     in.close(); 

    } finally { 
     connection.disconnect(); 
     System.out.println(result); 
    } 

} 
} 

这里是我的PHP控制器:

public function test(){ 

    $test=$_POST['fName']; 
    $all="This is a "; 
    $all=$all." ".$test; 
    echo $all; 



} 

当我刚刚发送URL请求,我得到的输出中为“这是一个”。所以它连接到网址和所有内容,但发送数据时,它不起作用。请帮忙!谢谢。

回答

1

您正在使用不同的流进行发布和获取。 你的邮政编码工作正常。

取代:

BufferedReader in = new BufferedReader(new InputStreamReader(
      url.openStream())); // different stream 

DataInputStream in = new DataInputStream (connection.getInputStream()); // same connection 

,它应该工作的罚款。

//编辑:这里没有任何不赞成的方法:

BufferedReader in = null; 
    try { 
     String line; 
     in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     while ((line = in.readLine()) != null) { 
      result += line; 
     } 
    } finally { 
     if (in != null) { 
      in.close(); 
     } 
    } 
+0

哦!非常感谢你 !现在它工作正常。顺便说一句,当我这样做: in.readLine()它说,该方法已弃用DataOutputStream中,应替换为我原来使用的BufferedReader线。那么如何解决这个问题呢? 另外如何使用bufferedReader而不是DataOutputStream发送POST数据。非常感谢您的帮助 ! :) – aradhya 2012-01-15 12:43:05

+0

你说得对。我添加了一个没有废弃方法的解决方案。至于发布使用BufferedReader:我不认为这是可能的(我可能是错的,但毕竟它是一个读者,而不是一个作家) – tim 2012-01-15 12:58:00

0

您明确指出您使用Java中的GET发送数据,但您正在读取的是PHP中的POST数据。

的Java(16):    connection.setRequestMethod("GET");
PHP(3):          $test=$_POST['fName'];

你需要改变其中的一个,所以他们都请使用POSTGET

+0

噢,对不起,我是用GET尝试它。它不能以任何方式工作 - GET或POST。 – aradhya 2012-01-15 03:48:10