android - HttpGet试图运行php脚本

时间:2014-11-29 21:37:33

标签: php android http httpclient

我试图从我的网络服务器上运行一个php脚本但是由于某种原因,请求仍然失败并转向捕获。不确定我还需要添加什么来简单地向服务器发送请求

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);
    }
}

我已经为我的AndroidManifest.xml添加了INTERNET权限

1 个答案:

答案 0 :(得分:0)

问题很可能是你从在UI线程上运行的OnClickListener调用phpRequest方法。所以你可以简单地在OnClickListener中启动一个新线程并像这样启动它:

new Thread() {
    public void run(){
        phpRequest();
    }
}.start();