如何从android表单发送请求到localhost URL ???

时间:2013-05-19 13:35:12

标签: java

我想将android表单数据发送到特定的URL(例如login.php页面"这是我的网站页面,它将验证来自DB保存记录的表单数据")

1 个答案:

答案 0 :(得分:1)

请参阅本教程,您已完成

http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

您实际上需要两个类才能执行此操作  1.你的活动  2. JSON Parser

以下是其中两个的示例代码,您可以根据自己的需要对其进行修改

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    static JSONArray jArr = null;

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());

        }
        Log.i("PHP Error", "["+json+"]");
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.getMessage() + json);
        }

        // return JSON String
        return jObj;

    }

    public JSONArray getAllMessages(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());

        }
        Log.i("PHP Error", "["+json+"]");
        // try parse the string to a JSON object
        try {
            jArr = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.getMessage() + json);
        }

        // return JSON String
        return jArr;

    }
}

活动

public class Home extends Activity {

    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    String message;

    private static String url_addmessage = "http://www.yourdomain.com/addmessage.php";

    private static final String TAG_SUCCESS = "success";

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

        final EditText et = (EditText)findViewById(R.id.editText1);

        Button b1 = (Button)findViewById(R.id.button1);
        Button b2 = (Button)findViewById(R.id.button2);

        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try{
                        message = et.getText().toString();

                        Log.i("message to be posted", message);

                        new RegisterMe().execute();
                }catch(Exception e){
                    Log.e("Exception while getting Message", e.getMessage().toString());
                }

                }
        });

        b2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(new Intent(Home.this, GetMessage.class));
            }
        });


    }

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

    class RegisterMe extends AsyncTask<String, String, String>{
        String Message=null;

        public boolean workdone(String Message){

            boolean x=false;
            if(Message == "Done"){
                x=true;
            }
            return x;
        }

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pDialog = new ProgressDialog(Home.this);
            pDialog.setMessage("Transaction In Progress... \n You Have The Right To Remain \n Silent & Patient :)");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {


            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("message", message));

            JSONObject json = jsonParser.makeHttpRequest(url_addmessage, "GET", params);

            Log.d("Create Response", json.toString());

            try{
                int success = json.getInt(TAG_SUCCESS);
                if(success == 1){
                    Message = "Done";
                    Log.d("Work Done", "Message Added");
                }
                else{

                    Log.d("Work Done", "Message Not Added");
                }
            } catch(JSONException e){
                e.printStackTrace();

            }

            return null;
        }

        protected void onPostExecute(String file_url){
            pDialog.dismiss();
            if(new RegisterMe().workdone(Message)){
                Toast.makeText(Home.this, "Message Added Successfully.",Toast.LENGTH_LONG).show();
            }
            else{
                Toast.makeText(Home.this, "Sorry There was some error in processing your request, please try after some time.",Toast.LENGTH_LONG).show();
            }


        }
    }

}