首页 > 代码库 > Android与服务器通信的方法之一(json)效率不高安全性不好

Android与服务器通信的方法之一(json)效率不高安全性不好

http通信,以xml或者json为载体,相互通信数据。

Android对于http的网络通信,提供了标准的java接口——httpURLConnection接口,以及apache的接口——httpclient接口。其中我自己用的比较多的而是httpclient这个接口,因为它的功能更为丰富很有效。

同时http通信也分为post方式和get的方式,两个相比较的话,post传送的数据量比较大,安全性也比较高。因此在做数据查询时,我会用get方式;而在做数据添加、修改或删除时,我就用Post方式
以下是基于httpclient接口,用get和post的方式通信的代码。
(get方式)

protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.login);

       TextView text = (TextView) this.findViewById(R.id.text_http);

       String httpurl = “http://10.0.2.2:8080/SIM_SERVER/org/Org-list”;

       //①httpget连接对象

       HttpGet httpRequest = new HttpGet(httpurl);

       //②取得httpclient的对象

       HttpClient httpclient = new DefaultHttpClient();

       try {

         //③请求httpclient,取得httpResponse

           HttpResponse httpResponse = httpclient.execute(httpRequest);

    //④判断请求是否成功     if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){             //⑤取得返回的字符串

              String strResult = EntityUtils.toString(httpResponse.getEntity());

              text.setText(strResult);

           }else{

              text.setText(“请求失败”);

           }

       } catch (ClientProtocolException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.printStackTrace();

       }

    }

(post方式)

protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       this.setContentView(R.layout.login);

       TextView text = (TextView) this.findViewById(R.id.text_http);

       //①http连接地址

       String url = “http://10.0.2.2:8080/SIM_SERVER/and/Android-test”;

        //②取得httppost连接对象

       HttpPost httpPost = new HttpPost(url);

        //③使用NameValuePair来保存要传递的Post参数

       List<NameValuePair> params = new ArrayList<NameValuePair>();

        //④添加要传递的参数

       params.add(new BasicNameValuePair(“parentId”, “0″));

 

       HttpEntity httpentity;

       try {

            //⑤设置字符集

           httpentity = new UrlEncodedFormEntity(params, “utf-8″);

            //⑥把字符集设置在请求request里面

           httpPost.setEntity(httpentity);

             //⑦取得httpclient

           HttpClient httpClient = new DefaultHttpClient();

             //⑧请求发送,并获得response

           HttpResponse httpResponse = httpClient.execute(httpPost);

//⑨判断请求是否成功     if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){              //⑩取得返回字符串

              String strResult = EntityUtils.toString(httpResponse.getEntity());

              text.setText(strResult);

           }else{

              text.setText(“请求失败”);

           }

       } catch (UnsupportedEncodingException e) {

           e.printStackTrace();

       } catch (ClientProtocolException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.printStackTrace();

       }

 

    }