[英]Very simple android-php communication does not work with http post
I have a really simple code that does not work. 我有一个非常简单的代码不起作用。 I just want to send a string from an android app to a php server.
我只想将字符串从android应用发送到php服务器。 Nothing fancy.
没有什么花哨。 I looked for similar questions but i didn't come up with anything.
我寻找类似的问题,但我没有提出任何建议。 I don't get the problem, the logcat does not give any error and everything seems working fine, but when i run my php script and send the string it does not happen anything.
我没有问题,logcat没有给出任何错误,一切似乎都正常,但是当我运行我的PHP脚本并发送字符串时,它什么也没发生。
this is my app's code 这是我的应用程式码
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("your_string", yourString));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(""); //my correct script adress
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Context context = getApplicationContext();
CharSequence text = "Succesfully uploaded!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
and this is php server 这是PHP服务器
<?php
if (isset($_POST['your_string']) && $_POST['your_string'] != '') {
$your_string = $_POST['your_string'];
echo 'received the string: ' . $your_string;
} else {
echo 'empty';
}
?>
Are you running your android code async? 您是否正在异步运行android代码? Consider using an Async Task .
考虑使用异步任务 。
Also be sure to add the Content type header: 另外,请确保添加“内容类型”标头:
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
You may also check the server response and log it so you know where's your problem, like this: 您也可以检查服务器响应并将其记录下来,以了解问题出在哪里,如下所示:
Log.d("Res",EntityUtils.toString(httpResponse.getEntity()));
Wish you luck ;) 祝您好运 ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.