java 通过 Post Android 发送数据到 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27513282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send Data Via Post Android to PHP
提问by Eric Teixeira
So, i'm trying to send message via Post in Android to PHP here is the Android Java Function:
所以,我试图通过 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
}
}
The PHP:
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);
?>
?>
The PHP is Just fine, I already tested it with a another Post and worked, but when the Android function tries $device_token dont recive any value and the SQL save a "" with the id at the table
PHP 很好,我已经用另一个 Post 测试过它并且工作过,但是当 Android 函数尝试 $device_token 时不接收任何值并且 SQL 在表中保存一个带有 id 的“”
回答by sec_aw
I use this code which is similar to yours, except the ResponseHandler. It works for me.
我使用的这段代码与你的相似,除了 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
}
回答by Pazuzu156
I'm sure there are better ways to do this, but this is how I usually handle post requests from Android:
我确信有更好的方法可以做到这一点,但这就是我通常处理来自 Android 的发布请求的方式:
<?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) . "')";
}
Also, since you're using POST instead of GET, the data being passed to the server isn't url encoded, so urldecode isn't needed here.
此外,由于您使用的是 POST 而不是 GET,因此传递给服务器的数据不是 url 编码的,因此此处不需要 urldecode。
回答by motoDrizzt
Code seems ok, only "strange" thing is:
代码似乎没问题,只有“奇怪”的是:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
because you are adding only ONE BasicNameValuePair to the list. Maybe that is the problem...?
因为您只将一个 BasicNameValuePair 添加到列表中。也许这就是问题所在......?
回答by BredeBS
I use this code in my current project, hope it's works for you too
我在我当前的项目中使用此代码,希望它也适用于您
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());
Also need this method in your class
在你的课堂上也需要这个方法
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();
}
}
hope I don't forgot anything, other way tell me
希望我没有忘记任何事情,其他方式告诉我
回答by Eric Teixeira
Guys the error was in my PHP
伙计们,错误出在我的 PHP 中
$device_token = urldecode($_POST['regid']);
This urldecode was messing out with my code haha
这个 urldecode 弄乱了我的代码哈哈
Thx for all help
感谢所有帮助