Android与server通信的方法之中的一个(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(); } }
posted on 2017-05-27 08:04 gavanwanggw 阅读(284) 评论(0) 编辑 收藏 举报