如何在android中发送带有参数的异步POST请求?

时间:2014-03-10 01:42:59

标签: java android post android-asynctask httprequest

所以我必须向php服务器发送异步POST请求。使用参数“密码”和值“EGOT”。如果成功,它将返回一个响应,它应该显示它花了多长时间。现在我知道我必须使用asyncTask但是我以前从未在android中做过这个以及如何开始或做什么的一些方向会很好。请帮帮我。我的代码如下。这是我到目前为止所得到的

     public class PingServerActivity extends Activity {

     private Button btn6;
    //private EditText value;

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

    btn6 = (Button) findViewById(R.id.btn_6);
    //value = (EditText) findViewById(R.id.textV5);

    pingButton();

}

public void pingButton() {

    btn6.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // this button would send the request to the server
            new PingPostTask().execute();

        }
    });

}

private class PingPostTask extends AsyncTask<String, Integer, String>{

    @Override
    protected String doInBackground(String... params) {
        postData(params[2]);
        return null;
    }

    protected void onPostExecute(String result) {
        //display result

        Toast.makeText(getApplicationContext(), "Request Sent", Toast.LENGTH_LONG).show();


    }

    public void postData(String Password) {
        // Create a new HttpClient and Post Header
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://ec2-54-243-205-92.compute-1.amazonaws.com/Test/ping.php");

                    try {
                        // Add your data
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("EGOT", Password));
                        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
                    }
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.ping_server, menu);
    return true;
}

}

0 个答案:

没有答案
相关问题