繁体   English   中英

非常简单的android-php通信不适用于http发布

[英]Very simple android-php communication does not work with http post

我有一个非常简单的代码不起作用。 我只想将字符串从android应用发送到php服务器。 没有什么花哨。 我寻找类似的问题,但我没有提出任何建议。 我没有问题,logcat没有给出任何错误,一切似乎都正常,但是当我运行我的PHP脚本并发送字符串时,它什么也没发生。

这是我的应用程式码

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();
}

这是PHP服务器

<?php
    if (isset($_POST['your_string']) && $_POST['your_string'] != '') {
        $your_string = $_POST['your_string'];
        echo 'received the string: ' . $your_string;
    } else {
        echo 'empty';
    }
?>

您是否正在异步运行android代码? 考虑使用异步任务

另外,请确保添加“内容类型”标头:

HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);

您也可以检查服务器响应并将其记录下来,以了解问题出在哪里,如下所示:

Log.d("Res",EntityUtils.toString(httpResponse.getEntity()));

祝您好运 ;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM