说明:
对于联网的APP来说,可能需要通过请求向服务器提交请求数据,也可能需要从服务器端获取数据显示
如何编码实现客户端与服务器端的交互尼?
JDK内置的原生API
HttpUrlConnection
android内置的包装API
HttpClient 浏览器
异步网络请求框架
Volley
Xutils
注意:
访问网络,需要申明权限:android.permission.INTERNET
访问网络的程序必须在分线程执行
使用HttpConnection
url:包含请求地址的类:
URL(path):包含请求路径的构造方法
openConnection():得到链接对象
HttpURLConnection:代表与服务器连接的类
setMethod("GET/POST"):设置请求方式
setConnectTimeout(time):设置连接超时时间,单位为ms
setReadTimeout(time):设置读取服务器返回数据的时间
connect():链接服务器
int getResponseCode():得到服务器返回的结果码
int getContentLength():得到服务器返回数据的长度(字节)
getOutputStream():返回一个指向服务器端的数据输出流
getInputStream():返回一个从服务器端返回的数据输入流
GET 请求方式:
/** * httpconnection发送GET请求 */ public void httpConnectionGet(View v){ //1、显示ProgressDialog final ProgressDialog dialog=ProgressDialog.show(this, null, "数据请求中..."); //2、启动分线程 new Thread(){ //3、在分线程中,发送请求,得到响应数据 public void run() { //1).得到path,并带上参数name=Tom //String path=key.getText().toString()+"?id=1"; try { //2).创建URL对象 URL url=new URL("http://192.168.1.33:8089/yabushan/userInfo/showUser?id=1"); //3).打开链接,得到httpURLConnection对象 HttpURLConnection connection=(HttpURLConnection) url.openConnection(); //4).设置请求方式,链接超时,读取数据超时 connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(6000); //5).链接服务器 connection.connect(); //6).发送请求,得到响应数据 //得到响应码,必须是200才读取 //得到InputStream,并读取成string InputStream is=connection.getInputStream(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int len=-1; while((len=is.read(buffer))!=-1){ baos.write(buffer, 0, len); } final String result=baos.toString(); baos.close(); is.close(); //4、在主线程中,显示得到的结果,移除dialog runOnUiThread(new Runnable() { @Override public void run() { value.setText(result); dialog.dismiss(); } }); //7、断开连接 connection.disconnect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }.start(); }
POST请求方式:
/** * 使用httpconnection发送POST请求 */ public void httpConnectionPost(View v ){ //1.显示progressDialog final ProgressDialog dialog=ProgressDialog.show(this, null, "正在加载中..."); //2.启动分线程 new Thread(new Runnable() { @Override public void run() { //3.在分线程发送请求,得到响应数据 try { //1).得到path String path=key.getText().toString(); //2).创建URL对象 //URL url=new URL(path); URL url=new URL("http://192.168.1.33:8089/yabushan/userInfo/showUser"); //3).打开连接 HttpURLConnection connection=(HttpURLConnection) url.openConnection(); //4).设置请求方式,链接超时,读取数据超时 connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); //5).链接服务器 connection.connect(); //6.发送请求得到响应数据 //的带输出流,写请求体:name=Tom OutputStream os=connection.getOutputStream(); String data="id=1"; os.write(data.getBytes("utf-8")); //得到响应码,必须是200才读取 int responseCode=connection.getResponseCode(); if(responseCode==200){ //得到ImputStream,并读取成String InputStream is=connection.getInputStream(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int len=-1; while((len=is.read(buffer))!=-1){ baos.write(buffer, 0, len); } final String result=baos.toString(); //在主线程,显示得到的结果,移除dialog runOnUiThread(new Runnable() { @Override public void run() { value.setText(result); dialog.dismiss(); } }); } os.close(); //7.断开连接 connection.disconnect(); } catch (Exception e) { // TODO: handle exception } } }).start();
使用HttpClient
GET请求:
/** * 使用httpclient发送get请求 * */ public void httpClientGet(View v ){ //1.显示progressDialog final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中。。。"); //2.启动分线程 new Thread(){ //3.在分线程中,发送请求,得到响应数据 @SuppressWarnings("deprecation") public void run() { try { //3-1.得到path,并带上参数name=Tom1&age=11 String pathString ="http://192.168.1.9:8089/yabushan/userInfo/showUser?id=1"; //3-2.创建Client对象 org.apache.http.client.HttpClient httpClient=new DefaultHttpClient(); //3-3.设置超时 HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 5000); //3-4.创建请求对象 HttpGet request = new HttpGet(pathString); //3-5.执行请求对象,得到响应对象 HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode==200){ //3-6.得到响应体文本 HttpEntity entity = response.getEntity(); final String result=EntityUtils.toString(entity); //4.要在主线程,显示数据,移除dialog runOnUiThread(new Runnable() { @Override public void run() { value.setText(result); dialog.dismiss(); } }); } //3-7.断开连接 httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); //如果出了异常,要移除dialog dialog.dismiss(); } }; }.start(); }
POST请求:
/** * 使用httpclient发送post请求 */ public void httpClientPost(View v){ //1.显示progressDialog final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中。。。"); //2.启动分线程 new Thread(){ //3.在分线程,发送请求,得到响应数据 public void run() { try { //3-1.得到path String path="http://192.168.1.9:8089/yabushan/userInfo/showUser"; //3-2.创建httpclient对象 HttpClient httpClient=new DefaultHttpClient(); //3-3.设置超时 HttpParams params =httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 5000); //4.创建请求对象 HttpPost request=new HttpPost(path); //设置请求体 Listparameters =new ArrayList (); //parameters.add(new BasicNameValuePair("name", "Tom4")); //parameters.add(new BasicNameValuePair("age", "14")); parameters.add(new BasicNameValuePair("id", "1")); HttpEntity entity = new UrlEncodedFormEntity(parameters); request.setEntity(entity); //5.执行请求对象,得到响应对象 HttpResponse response = httpClient.execute(request); int statusCode =response.getStatusLine().getStatusCode(); if(statusCode==200){ //6.得到响应体文本 entity = response.getEntity(); final String result = EntityUtils.toString(entity); //7.主线程,显示数据,移除dialog runOnUiThread(new Runnable() { @Override public void run() { value.setText(result); dialog.dismiss(); } }); } //8.断开连接 httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); dialog.dismiss(); } }; }.start(); }
使用volley请求
get请求:
/** * 使用volley发送get请求 * */ public void vo_get(View v){ //1.创建请求队列对象(一次) final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中"); //2.创建请求对象StringRequest String path = "http://localhost:8089/yabushan/userInfo/showUser?id=1"; StringRequest request = new StringRequest(path, new Listener() { @Override public void onResponse(String response) {//在主线程执行 value.setText(response); dialog.dismiss(); } }, null); //3.将请求添加到队列中 queue.add(request); }
post请求:
/** * 使用valley发送post请求 */ public void vo_post(View v){ final ProgressDialog dialog= ProgressDialog.show(this, null, "正在请求中。。。"); //创建请求对象StringRequest String pathString ="http://localhost:8089/yabushan/userInfo/showUser"; StringRequest request = new StringRequest(pathString, new Listener() { @Override public void onResponse(String response) { value.setText(response); dialog.dismiss(); } }, null){ //重写此方法返回参数的map作为请求体 @Override protected Map getParams() throws AuthFailureError { Map map = new HashMap (); map.put("id", "1"); return map; } }; //将请求添加到队列中 queue.add(request); }