Android开发实践 网络通信 URL、URLConnection、HttpClient
Android支持JDK提供的URL、URLConnection等网络通信API,另外Android还内置了HttpClient。
Java基于TCP和UDP协议的网络通信请查看http://blog.csdn.net/smartbetter/article/details/51340441
1.URL
URL(Uniform Resource Locator)对象代表统一资源定位符,它是指向互联网“资源”的指针。
URL格式:protocol://host:port/resourceName
拓展:JDK还提供了Uri(统一资源标识符)类
当我们获取到URL对象后,即可调用如下方法来访问URL对应的资源:
String getFile():获取资源名String getHost():获取主机名String getPath():获取路径部分int getPort():获取端口号String getProtocol():获取协议名称String getQuery():获取查询字符串部分URLConnection openConnection():返回一个URLConnection对象(表示到URL所引用的远程对象的连接)InputStream openStream():打开连接,并返回一个用于读取该URL资源的InputStream
2.使用URL读取网络资源
URL对象的openStream()方法可以非常方便的读取该URL资源的InputStream。
public class URLTest extends Activity { // 从网络上下载得到的图片 Bitmap bitmap; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread() { public void run() { try { URL url = new URL("http://avatar.csdn.net/D/F/D/1_smartbetter.jpg"); /** * 解析输入流中的图片 */ InputStream is = url.openStream(); // 打开URL对应资源的输入流 bitmap = BitmapFactory.decodeStream(is); // 从InputStream中解析出图片 is.close(); /** * 使用IO将输入流中的图片下载到本地 */ is = url.openStream(); // 再次打开URL对应资源的输入流 OutputStream os = openFileOutput("icon.jpg", MODE_WORLD_READABLE); // 打开手机文件对应的输出流 byte[] buff = new byte[1024]; int hasRead = 0; // 将URL对应的资源下载到本地 while((hasRead = is.read(buff)) > 0) { os.write(buff, 0 , hasRead); } is.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } } }.start(); }}
注意:需要添加访问网络权限
3.使用URLConnection提交请求
URL的openConnection()方法将返回一个URLConnection对象(表示应用程序和URL之间的通信连接),程序可通过URLConnection实例向该URL发送请求,读取URL引用的资源。
如下GetPostUtil工具类向Web站点发送GET请求、POST请求,并取得响应:
public class GetPostUtil { /** * 向指定URL发送GET请求 * @param url 请求参数,name1=value1&name2=value2 * @param params * @return 远程资源的响应 */ public static String doGet(String url, String params) { String result = ""; BufferedReader in = null; try { String urlName = url + "?" + params; URL realUrl = new URL(urlName); URLConnection conn = realUrl.openConnection(); // 打开和URL之间的连接 // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.connect(); // 建立实际的连接 Map<String, List<String>> map = conn.getHeaderFields(); // 获取所有响应头字段 // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + ":" + map.get(key)); } // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { System.out.println("请求异常!" + e); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * 向指定URL发送POST请求 * @param url * @param params 请求参数,name1=value1&name2=value2 * @return 远程资源的响应 */ public static String doPost(String url, String params) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); // 打开和URL之间的连接 // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); out.print(params); // 发送请求参数 out.flush(); // flush输出流的缓冲 // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { System.out.println("请求异常!" + e); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }}
4.使用HttpURLConnection
HttpURLConnection继承了URLConnection做了改进,增加了一些用于操作HTTP资源的便捷方法:
int getResponseCode():获取服务器的响应代码String getResponseMessage():获取服务器的响应消息String getRequestMethod():获取发送请求的方法void setRequestMethod(String method):设置发送请求的方法
5.使用HttpClient
HttpClient是Apache的一个开源项目,可用于发送HTTP请求,接受Http响应,不会缓存服务器的响应,不能执行HTML中JS代码,也不会对页面进行任何解析、处理。HttpClient就是一个增强版的HttpURLConnection。
接下来看看HttpClient的用法:
public class HttpClientTest extends Activity { HttpClient httpClient; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ... httpClient = new DefaultHttpClient(); // 创建DefaultHttpClient对象 ... } /** * Get请求 */ public void doHttpClientGet(View view) { new Thread() { @Override public void run() { // 创建一个HttpGet对象 HttpGet get = new HttpGet("http://192.168.1.10:8080/server/page.jsp"); try { // 发送GET请求 HttpResponse httpResponse = httpClient.execute(get); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { // 读取服务器响应 BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); String line = null; while ((line = br.readLine()) != null) { System.out.println("服务器响应:"+line); } } } catch (Exception e) { e.printStackTrace(); } } }.start(); } /** * Post请求 * 模拟post请求登录 */ public void doHttpClientPost(View view) { final String name = "zhangsan"; final String pass = "123"; new Thread() { @Override public void run() { try { HttpPost post = new HttpPost("http://192.168.1.10:8080/server/login.jsp"); // 如果传递参数量大的话可以对传递参数进行封装 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("pass", pass)); // 设置请求参数 post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 发送POST请求 HttpResponse response = httpClient.execute(post); // 返回响应 if (response.getStatusLine().getStatusCode() == 200) { String msg = EntityUtils.toString(response.getEntity()); Looper.prepare(); System.out.println(msg); Looper.loop(); } } catch (Exception e) { e.printStackTrace(); } } }.start(); }}
6.使用第三方网络请求框架
(1)OkHttp
(2)Retrofit
(3)Android Volley
(4)android-async-http
(5)ion
(6)robospice
(7)android-lite-http
(8)androidquery
(9)xUtils3框架
(10)Afinal框架
更多相关文章
- android获取gps坐标
- Android利用Fiddler进行网络数据抓包
- Android(安卓)Tip1:获取 android 每个 app 内存限制大小
- android sim卡 TelephonyManager类:Android手机及Sim卡状态的获取
- Android札记
- (二)Android系统信息
- android与服务端通信
- Android获取运营商代码
- android UDID获取:android 设备SN的获取 续 android 设备唯一码的