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 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题