所以,我正在尝试通过 Android 中的 Post 向 PHP 发送消息 这是 Android Java 函数:
//enviando para o backend
private void SendtoPHP(String reg) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://bubbledev.com.br/gcm/getdevice.php");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("regid", "" + reg ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
PHP:
<?php
include 'conecta.php';
$device_token = urldecode($_POST['regid']);
$sql = "INSERT INTO corposa.deviceandroid"
. " (id,device_token)"
. " VALUES (NULL,'$device_token')";
mysqli_query($con,$sql);
?>
PHP 很好,我已经用另一篇文章测试了它并且可以工作,但是当 Android 函数尝试 $device_token 时没有收到任何值,并且 SQL 会在表中保存一个带有 id 的“”
我使用的代码与您的类似,除了 ResponseHandler 之外。 它对我有用。
HttpClient Client = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", sID));
nameValuePairs.add(new BasicNameValuePair("etc", sETC));
try {
String SetServerString = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://your-url.com/script.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = httpclient.execute(httppost, responseHandler);
} catch(Exception ex) {
// failed
}
我确信有更好的方法可以做到这一点,但这就是我通常处理来自 Android 的 post 请求的方式:
<?php
{
$input = json_encode(file_get_contents("php://input"));
$deviceToken = $input->regId;
mysqli_query($connection, "INSERT INTO corposa.deviceandroid (`id`, `device_token`) VALUES(NULL, '" . mysqli_real_escape_string($deviceToken) . "')";
}
此外,由于您使用的是 POST 而不是 GET,因此传递到服务器的数据没有进行 url 编码,因此这里不需要 urldecode。
代码看起来没问题,唯一“奇怪”的是:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
因为您只向列表中添加一个 BasicNameValuePair。也许这就是问题所在......?
我在当前的项目中使用此代码,希望它也适合您
Map<String, String> kvPairs = new HashMap<String, String>();
kvPairs.put("regid", reg);
HttpClient httpclient = this.getNewHttpClient();
HttpPost httppost = new HttpPost("http://bubbledev.com.br/gcm/getdevice.php");
if (kvPairs != null && kvPairs.isEmpty() == false) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
String k, v;
Iterator<String> itKeys = kvPairs.keySet().iterator();
while (itKeys.hasNext()) {
k = itKeys.next();
v = kvPairs.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
HttpResponse response;
response = httpclient.execute(httppost);
String responseString = EntityUtils.toString(response.getEntity());
你的班级也需要这个方法
public static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new RecorridoSSL(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
希望我没有忘记任何事情,有其他方式请告诉我
伙计们,错误出在我的 PHP 中
$device_token = urldecode($_POST['regid']);
这个 urldecode 搞乱了我的代码哈哈
感谢所有帮助
包 com.example.project_name
导入 android.os.Bundle
导入 android.widget.TextView 导入 androidx.appcompat.app.AppCompatActivity
导入com.android.volley.Response
导入com.android.volley.toolbox.StringRequest 导入 com.android.volley.toolbox.Volley
MainActivity 类:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView = findViewById<TextView>(R.id.textView)
val url = "https://path/index.php"
val queue = Volley.newRequestQueue(this)
val stringRequest = object : StringRequest(
Method.POST, url,
Response.Listener { response ->
textView.text = response!! // Changed 'e' to 'd' for debug logging
},
Response.ErrorListener { error ->
textView.text = error.toString()
}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>() // Use HashMap instead of deprecated HasMap
params["key1"] = "hello" // No duplicate key
params["key2"] = "world" // Added second key-value pair
return params
}
// 重写 fun getHeaders(): Map
queue.add(stringRequest)
}
}