簡體   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