我正在使用 Web 服务将用户信息发送到 MySQL,但是当我尝试回显这些值时,PHP 没有返回发布的值,并给我:
Notice: Undefined index: user_name in C:\xampp\htdocs\webservice\sign_up.php on line 5
我的代码:
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://10.0.2.2/webservice/sign_up.php");
ArrayList<NameValuePair> post = new ArrayList<NameValuePair>(3);
post.add(new BasicNameValuePair("user_name", name));
post.add(new BasicNameValuePair("user_email", email));
post.add(new BasicNameValuePair("user_password", password));
request.setEntity(new UrlEncodedFormEntity(post));
HttpResponse response = client.execute(request);
int status = response.getStatusLine().getStatusCode();
Log.i("data posted, status = " , Integer.toString(status));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
}
和PHP:
<?php
$user = $_POST["user_name"];
echo $user;
?>
最佳答案
将字符串从 android 客户端传递到 PHP 的示例代码
Android 客户端部分
下面的代码将使您的 Android 应用程序能够与网页对话。
注意:您还需要在 android.manifest 文件中启用互联网使用权限。
<uses-permission
android:name="android.permission.INTERNET" />
安卓应用代码
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.URL.com/yourpage.php");
//This is the data to send
String MyName = 'adil'; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
PHP代码
<?php
echo $_POST["action"];
?>
关于PHP 不从 Android Post 值返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22173158/