我遇到了一个错误,但我似乎无法弄清楚原因。我正在尝试将数据发布到 php 文件,但陷入了捕获错误。我收到的消息是“数据未发送”,但在它之前我收到的消息是“数据已准备好”。有人可以看一下并帮助我确定我的问题是什么吗?
安卓方法:
public void insertToDB(String data){
try {
HttpClient client=new DefaultHttpClient();
HttpPost getMethod=new HttpPost("http://shawnc.webuda.com/upload.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("RPM",data));
getMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
String toastText = "Data was prepared";
Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
try {
client.execute(getMethod);
toastText = "Data has been sent: " + data;
Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
}catch(Exception e){
toastText = "Data was not sent";
Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
String toastText = "Data could not be prepared";
Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
}
}
和我的 php 文件:
<?
$hostname_host ="MYSQLxxxxx.Smarterasp.net";
$database_host ="db_xxxxx_db";
$username_host ="9xxxxx_db";
$password_host ="password";
$server= mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db("db_xxxxx_db");
$sql=mysql_query("INSERT INTO driverdata (RPM)VALUES('".$_REQUEST['RPM']."')");
$r=mysql_query($sql);
if(!$r)
echo "Error in query: ".mysql_error();
mysql_close();
?>
最佳答案
当您不知道问题出在哪里时,请尝试将 PHP 脚本替换为
<?php
echo "OK";
?>
并尝试读取 PHP 的响应
try {
HttpResponse response = client.execute(getMethod);
toastText = "Data has been sent: " + data;
当您得到响应时,OK 问题出在 PHP 中。
当我使用 httppost 时,我使用此代码来获取响应。当我有响应时,http 请求就OK了。
HttpClient client = new DefaultHttpClient(httpParameters);
client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
client.getParams().setParameter("http.socket.timeout", 2000);
client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
httpParameters.setBooleanParameter("http.protocol.expect-continue", false);
HttpPost request = new HttpPost("http://xxxxxx.com/upload.php");
request.getParams().setParameter("http.socket.timeout", 5000);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("RPM",data));
try {
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, HTTP.UTF_8);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
//do with response
关于java - 使用 android 发布数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26249169/