【发布时间】:2011-03-14 03:22:09
【问题描述】:
我正在制作一个 android 应用程序,我需要使用 post 数据将从数据中收集的一些数据发送到服务器 php 文件,并从 php 文件中获取回显文本并显示它。我有这种格式的帖子变量->“name=xyz&home=xyz”等等。我正在使用下面的类来发布,但是服务器上的 php 文件没有得到发布的 vars。有人可以告诉我有什么问题或任何其他方法可以做我想做的事情吗?
package xxx.xxx.xxx;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetUtil {
public static String UrlToString(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.write(urlParameters.getBytes("UTF-8"));
wr.flush ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
我从 php 文件得到响应,但是 php 文件没有得到 post 数据。
【问题讨论】: