dqlhsm9820 2014-11-29 21:37
浏览 50
已采纳

android - HttpGet试图运行php脚本

I'm trying to run a php script from my web server But for some reason the request keeps failing and going to the catch. Not sure what else I need to add to simply send a request to the server

public class MainActivity extends Activity {

    public void phpRequest()
    {
         HttpClient client = new DefaultHttpClient();
         final String url = "http://192.168.1.103/lock.php";

         try
         {
             client.execute(new HttpGet(url));
         }
         catch(Exception e)
         {
            Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show(); 
         }


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn_lock = (Button)findViewById(R.id.lock);
        Button btn_sleep = (Button)findViewById(R.id.sleep);
        Button btn_shutdown = (Button)findViewById(R.id.shutdown);

        btn_lock.setOnClickListener(new OnClickListener()
        {


            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG).show();

                phpRequest();
            }

        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

I have already added INTERNET permission to my AndroidManifest.xml

  • 写回答

1条回答 默认 最新

  • dtvq4978 2014-11-29 21:50
    关注

    The problem most likely is that you are calling the phpRequest method from the OnClickListener which runs on the UI thread. So you could simply start a new thread in the OnClickListener and start it like this:

    new Thread() {
        public void run(){
            phpRequest();
        }
    }.start();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用
  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启