Java 如何将请求从android表单发送到本地主机URL???

Java 如何将请求从android表单发送到本地主机URL???,java,Java,我想将android表单数据发送到特定的URL(如login.php页面“这是我的网站的一个页面,将验证DB保存记录中的表单数据”)查看本教程,您就完成了 要做到这一点,实际上需要两个类 1.你单位 2.JSON解析器 这是其中两个的示例代码,您可以根据自己的需要进行修改 public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static Strin

我想将android表单数据发送到特定的URL(如login.php页面“这是我的网站的一个页面,将验证DB保存记录中的表单数据”)

查看本教程,您就完成了

要做到这一点,实际上需要两个类 1.你单位 2.JSON解析器

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

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;

    }
}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
静态JSONArray jArr=null;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}          
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
为“utf-8”)、8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
Log.i(“PHP错误”,“[”+json+“]”);
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.getMessage()+JSON);
}
//返回JSON字符串
返回jObj;
}
公共JSONArray getAllMessages(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}          
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
为“utf-8”)、8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
Log.i(“PHP错误”,“[”+json+“]”);
//尝试将字符串解析为JSON对象
试一试{
jArr=新JSONArray(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.getMessage()+JSON);
}
//返回JSON字符串
返回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();
            }


        }
    }

}
公共类主页扩展活动{
私人对话;
JSONParser JSONParser=新的JSONParser();
字符串消息;
私有静态字符串url_addmessage=”http://www.yourdomain.com/addmessage.php";
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
最终EditText et=(EditText)findViewById(R.id.editText1);
按钮b1=(按钮)findViewById(R.id.button1);
按钮b2=(按钮)findViewById(R.id.button2);
b1.setOnClickListener(新的OnClickListener(){