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;
	}

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

 <uses-permission android:name="android.permission.INTERNET" />


 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liranke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值