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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么