将数据从 Android 发送到 PHP 页面

发布于 2024-12-18 19:09:58 字数 949 浏览 0 评论 0原文

我现在正在尝试将数据从 Android 应用程序(带有模拟器)发送到 Web 服务器(一个 php 页面)。首先,我用模拟器尝试了这个程序并且它可以工作。之后,我用电话尝试了这个程序,出现了异常:

--> IO 异常:操作超时。

我的代码的一部分:

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://10.0.2.2:90/takeDatas.php");
try {                   
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("enlem", latitude ));
    nameValuePairs.add(new BasicNameValuePair("boylam", longitude ));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    Toast.makeText(ReportLocationActivity.this, "Client protokol exception ", Toast.LENGTH_LONG).show();
} catch (IOException e) {
    Toast.makeText(ReportLocationActivity.this, "IO exception "+e.getMessage(), Toast.LENGTH_LONG).show();
}

我希望你能帮助我。 提前致谢。

I am trying sending data from android application (with emulator) to web server (a php page) nowadays. Firstly, I had tried this program with emulator and it was working. After that, I tried this program with telephone and an exception occurred :

--> IO Exception : The operation timed out.

One part of my code :

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://10.0.2.2:90/takeDatas.php");
try {                   
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("enlem", latitude ));
    nameValuePairs.add(new BasicNameValuePair("boylam", longitude ));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    Toast.makeText(ReportLocationActivity.this, "Client protokol exception ", Toast.LENGTH_LONG).show();
} catch (IOException e) {
    Toast.makeText(ReportLocationActivity.this, "IO exception "+e.getMessage(), Toast.LENGTH_LONG).show();
}

I hope you will help me.
Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心凉 2024-12-25 19:09:58

模拟器中的 localhost 是模拟器本身。不确定Windows环境,但在Linux下我可以通过IP 10.0.2.2从模拟器访问主机系统上的Web服务器(注意:这个IP不是我的Linux的IP系统,但从模拟器中可以通过该 IP 准确访问)。
您可以在此处了解有关模拟器网络的更多信息。

The localhost in emulator is the emulator itself. Not sure about Windows environment, but under Linux I was able to get an access to web server on the host system from the emulator by IP 10.0.2.2 (Note: this IP is not the IP of my Linux system, but from the emulator it's accessible exactly by this IP).
You can read more about emulator networking here.

尽揽少女心 2024-12-25 19:09:58

是的,您必须使用 http://10.0.2.2/simpleSending.php

HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2/yourpage.php");

    //This is the data to send
    String MyName = "flower"; //any data to send

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("action", MyName));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpclient.execute(httppost, responseHandler);


        //This is the response from a php application
        String reverseString = response;
        Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();

    } catch (ClientProtocolException e) {
        Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
        // TODO Auto-generated catch block
    } catch (IOException e) {
        Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
        // TODO Auto-generated catch block
    }

Yes instead of using 127.0.0.1 or http://localhost:90 , you have to use http://10.0.2.2/simpleSending.php.

HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2/yourpage.php");

    //This is the data to send
    String MyName = "flower"; //any data to send

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("action", MyName));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpclient.execute(httppost, responseHandler);


        //This is the response from a php application
        String reverseString = response;
        Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();

    } catch (ClientProtocolException e) {
        Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
        // TODO Auto-generated catch block
    } catch (IOException e) {
        Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
        // TODO Auto-generated catch block
    }
樱&纷飞 2024-12-25 19:09:58

由于异步方法调用可能会生成此错误。因此您需要将该异步方法包装在类中。
这是代码:

 package com.example.asynchttppost;

    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 android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    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.activity_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);
        }


        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]);
                return null;
            }

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

            public void postData(String valueIWantToSend) {
                // Create a new HttpClient and Post Header
                String url= "your website url";
                //String url ="http://10.0.2.2/remoteaccess/";
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);

                try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppost);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }
            }

        }
    }

this error might get generated because of asynchronous method call.So you need to wrap that Asynchronous method in a class.
Here is the code:

 package com.example.asynchttppost;

    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 android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    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.activity_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);
        }


        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]);
                return null;
            }

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

            public void postData(String valueIWantToSend) {
                // Create a new HttpClient and Post Header
                String url= "your website url";
                //String url ="http://10.0.2.2/remoteaccess/";
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);

                try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppost);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }
            }

        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文