非常简单的android-php通信不与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()));

祝你好运

最新更新