1.什么是Http请求?
2.什么是HttpUrlConnection?
在Android开发中网络请求是最常用的操作之一, Android SDK中对HTTP(超文本传输协议)也提供了很好的支持,这里包括两种接口:
1、标准Java接口(java.NET) —-HttpURLConnection,可以实现简单的基于URL请求、响应功能;
2、Apache接口(org.appache.http)—-HttpClient,使用起来更方面更强大。
但在android API23的SDK中Google将HttpClient移除了。Google建议使用httpURLconnection进行网络访问操作。
HttpURLconnection是基于http协议的,支持get,post,put,delete等各种请求方式,最常用的就是get和post。
3.如何使用HttpUrlConnection?
GET请求
/** * 从网络获取json数据,(String byte[})
* @param path * @return */ public static String getJsonByInternet(String path){ try { URL url = new URL(path.trim()); //打开连接 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if(200 == urlConnection.getResponseCode()){ //得到输入流 InputStream is =urlConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while(-1 != (len = is.read(buffer))){ baos.write(buffer,0,len); baos.flush(); } return baos.toString("utf-8"); } } catch (IOException e) { e.printStackTrace(); } return null; }
POST请求
//获取其他页面的数据 /** * POST请求获取数据 */ public static String postDownloadJson(String path,String post){ URL url = null; try { url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST");// 提交模式 // conn.setConnectTimeout(10000);//连接超时 单位毫秒 // conn.setReadTimeout(2000);//读取超时 单位毫秒 // 发送POST请求必须设置如下两行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); // 获取URLConnection对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()); // 发送请求参数 printWriter.write(post);//post的参数 xx=xx&yy=yy // flush输出流的缓冲 printWriter.flush(); //开始获取数据 BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len; byte[] arr = new byte[1024]; while((len=bis.read(arr))!= -1){ bos.write(arr,0,len); bos.flush(); } bos.close(); return bos.toString("utf-8"); } catch (Exception e) { e.printStackTrace(); } return null; }