php - Web 服务器未使用 Async Http 从 Android 应用程序接收 POST - localhost

标签 php android apache post localhost

我正在尝试开发一个 Android 应用程序,将一个简单的字符串发送到网页并让网页存储该字符串。我最近安装了 BitnamiWAMP 堆栈以使用 PHP 代码,并一直通过本地主机运行我的 PHP。我遵循了一些教程并遇到了一些使用 AsynchPost 发布数据的示例。我的 PHP 代码从不返回字符串。我不知道从哪里开始调试我的应用程序,因为我的 PHP 代码和 Android 应用程序没有返回任何错误。有没有人对可能出现的问题有任何建议?任何帮助/建议将不胜感激。我在 Apache 2.2 服务器上运行我的 php 脚本,并使用 android 模拟器发送数据。

主要 Activity

package com.example.post;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    private EditText value;
    private Button btn;
    private ProgressBar pb;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        value=(EditText)findViewById(R.id.editText1);
        btn=(Button)findViewById(R.id.button1);
        pb=(ProgressBar)findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);
        btn.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
            if(value.getText().toString().length()<1){

                // out of range
                Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
            }else{
                pb.setVisibility(View.VISIBLE);
                new MyAsyncTask().execute(value.getText().toString());      
            }


    } 

    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

        @Override
        protected Double doInBackground(String... params) {
            // TODO Auto-generated method stub
            postData(params[0]);
            Log.v("parameters = ", params[0]);
            return null;
        }

        protected void onPostExecute(Double result){
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }

        public void postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/hello.php");
            HttpResponse response = null;
            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("data", valueIWantToSend));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                String res = EntityUtils.toString(response.getEntity());
                Log.v("Response = ", res);

            } catch (ClientProtocolException e) {
                e.printStackTrace();
                // TODO Auto-generated catch block
            } catch (IOException e) {
                e.printStackTrace();
                // TODO Auto-generated catch block
            }
            //return response.toString();
        }

    }
}

主.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Enter Something Below:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:hint=""
        >

        <requestFocus />
    </EditText>

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/progressBar1"
        android:layout_marginTop="24dp"
        android:text="Submit" />

</RelativeLayout>

list

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.post.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

PHP代码

<?php

//echo "hello";

if(isset($_POST['data'])) {

$message = $_POST["data"];

$filename = "androidmessages.txt";

ini_set("log_errors", 1);

ini_set("error_log", $filename);

error_log($message);
$file = fopen("test.txt", "w");
echo fwrite($file, $message);
fclose($file);

}
//echo $message;
//file_put_contents($filename, $message);

?>

最佳答案

如果有人再次遇到这个问题 - 修复它。请参阅更新的代码 - 由于某种原因 file_put_contents 无法正常工作并且 php 从未设置数据。 fwrite 是一个更好的选择,而 ERROR_LOG 是另一种将一些内容写入文件的方法,尽管它写入时带有时间戳。

关于php - Web 服务器未使用 Async Http 从 Android 应用程序接收 POST - localhost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24069127/

相关文章:

java - 如何在 Android 中替换 JSON 字符串中的 HTML 转义字符

java - Android:File()的 Assets 文件夹路径?

apache - 使用简单的名称访问局域网上的本地网络服务器,例如 http ://example. intranet.com

apache - 如何阻止其他人的域名指向我的Apache托管网站?

php - 与数据透视表 Laravel 的 Eloquent 和内部循环的关系

php - 如何在 Laravel 中搜索奇怪的字符?

android - 这个 Handler 类应该是静态的,否则可能会发生泄漏 : IncomingHandler

apache - 无法删除 Apache noindex 页面

php - 在 php 中创建时间戳并替换旧日期

php - 查询3个mysql表以创建HTML表