我正在尝试从android通过“httppost”方法向web服务发送一些变量(或数据)。这是代码。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsitename.com/webservice/register.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("fname", et3.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("lname", et4.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("userid", et5.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", et6.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
以下是Register.php文件代码。
<?php
$host = "localhost";
$user = "myusername";
$pass = "mypass";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$userid = $_POST['userid'];
$pass = $_POST['pass'];
$db_select=mysql_select_db("the_db");
if(!$db_select){
die(mysql_error());
echo "error";
}
$query= "INSERT INTO USERS(fname, lname, userid, pass)
VALUES ('{$fname}', '{$lname}', '{$userid}', '{$pass}'); " ;
if($medo=mysql_query($query)){
header("localhost/filename");
exit;
}else{
echo"<p> Error</p>";
die(mysql_error());
}
当我尝试运行它时,给我一个错误。它在我的设备上说“YourApp已停止工作”。可能是nullpointer异常或类似的东西。我不知道这是否是将名称和密码等简单变量发送到register.php的正确方法。你能告诉我这里的问题是什么吗?
答案 0 :(得分:3)
请查看LogCat输出。它应该说你在哪个班级的哪一行有例外。如果需要帮助,请在此处发布logcat输出。我还建议您查看Android Asynchronous Http Client。它极大地简化了HTTP通信。 HTTP POST示例:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("fname", et3.getText().toString());
rp.put("lname", et4.getText().toString());
rp.put("userid", et5.getText().toString());
rp.put("pass", et6.getText().toString());
client.post("http://mywebsitename.com/webservice/register.php", rp, new AsyncHttpResponseHandler() {
@Override
public final void onSuccess(String response) {
// handle your response here
}
@Override
public void onFailure(Throwable e, String response) {
// something went wrong
}
});