使用这种技术的Android请求/响应安全吗?

时间:2013-07-07 05:48:49

标签: android rest httprequest

我只是想知道这是一种在Android上进行通信的好方法还是有更安全和更好的方式?

  btnInsert.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) 
        {
            //Create the request
            **String url** = "http://10.0.2.2:80/practice/mysql_demo/inserting.php?";
            url = url + "txtName=" + txtName.getText().toString() + "&";
            url = url + "txtAge=" + txtAge.getText().toString() + "&";
            url = url + "txtAddress=" + txtAddress.getText().toString() + "&";
            url = url + "txtContact=" + txtContact.getText().toString() + "&";
            url = url + "txtOtherInformation=" + txtOtherInformation.getText().toString();

            **executeQuery(url)**;
            selectRecords(lstStudents);
        }
});
**public void executeQuery(String url)**
{
    //execute the URL, and get the result
    try
    {
        HttpClient http = new DefaultHttpClient();
        HttpGet http_get = new HttpGet(url);
        HttpResponse http_response = http.execute(http_get);
        HttpEntity http_entity = http_response.getEntity();
        BufferedReader br = new BufferedReader(
                new InputStreamReader(http_entity.getContent()));
        String result = br.readLine();

        Toast.makeText(PHPDemo.this, result, Toast.LENGTH_LONG).show();
    }
    catch (Exception ex)
    {
        Toast.makeText(PHPDemo.this, ex.getMessage(), Toast.LENGTH_LONG).show();
    }
}

2 个答案:

答案 0 :(得分:1)

您必须使用threadAsynctask进行与网络相关的操作。

 HttpResponse http_response = http.execute(http_get);  

Post Honeycomb你会得到NetworkOnMainThreadException。使用AsyncTask或使用线程。

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

对于Asynctask

http://developer.android.com/reference/android/os/AsyncTask.html

注意:您无法从后台线程更新ui。你可以在ui线程上更新ui。

答案 1 :(得分:0)

@Raghunandan是对的。除此之外,我建议单独对查询参数名称和值进行URL编码。您可以将URLEncoder.encode"UTF-8"一起用作编码。

既然你问过是否有更好的方法:

对于较新的Android版本,您可能需要考虑HttpUrlConnection over Apache's HttpClient

您可能还想查看一些Android networking libraries,例如Volley或OkHttp等。