> 文档中心 > Android基础#43:Android网络数据请求之HttpURLConnection

Android基础#43:Android网络数据请求之HttpURLConnection

内容简介:

本节展示网络数据请HttpURLConnection的post请求方式。
在Android应用程序中,经常需要进行网络数据的请求。Android提供了很多网络数据请求的标准接口,还有很多第三方的网络数据请求库,httpclient,okhttp...可谓是百花齐放。HttpURLConnection是最基础最简单的Android网络数据接口API。如果你的数据量不是很大的话,可以用HttpURLConnection来进行数据请求。

 

代码示例:

post工具类:HttpUtils.java的核心代码如下:

 

   public static byte[] post(String url, String data) {     return post(url, data.getBytes());     }     /** * 採用post请求的方式 *  * @param url: http url * @param data: post数据 * @return 请求得到的数据 */public static byte[] post(String url, byte[] data) {InputStream is = null; OutputStream out = null;try {URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(500);conn.setRequestMethod("POST");// 设置请求的内容的类型conn.setRequestProperty("Content-Type", "application/text");conn.setRequestProperty("Content-Length", data.length());httpConn.setRequestProperty("Charset", "UTF-8");// 获取http连接的输出流os = conn.getOutputStream();// 向server写入数据os.write(data);if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) { // 请求成功ByteArrayOutputStream bos = new ByteArrayOutputStream();is = conn.getInputStream(); //读取服务器返回的数据byte[] buf = new byte[1024]; int len; while ((len = is.read(buf, 0, 1024)) != -1) {     bos.write(buf, 0, len); } return bos.toByteArray();} else {// 请求失败return null;}} catch (Exception e) {e.printStackTrace();}finally {     try {  if (out != null)      out.close();  if (is != null)      is.close();     } catch (IOException e) {  e.printStackTrace();     } }return null;}

当然,需要在配置文件中设置访问网络权限: