原生HttpUrlConnection

今天研究了下原生请求网络的形式

//1,new 一个线程

new Thread(new Runnable() {
    @Override
    public void run() {
        HttpURLConnection connection = null;
        try {
2,请求的地址:如  http:www.baidu.com
            URL mUrl = new URL(HttpUtil.APIADD);
            connection = (HttpURLConnection) mUrl.openConnection();
            connection.setDoOutput(true);   //需要输出
            connection.setDoInput(true);   //需要输入
3,请求方式,post还是get,
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

4,post请求需要的参数传递
            //建立输入流,向指向的URL传入参数
            String params = "api_id=" + api_id
                    + "&client=2"
                    + "&version=" + JPushReceiver.F_VERSION
                    + "&phone_id=" + phone_id
                    + "&phone_os=" + phone_os
                    + "&phone_resolution=" + phone_resolution
                    + "&push_id=" + jps_id
                    + "&push_type=2"
                    + "&api_time=" + time
                    + "&api_md5=" + api_md5
                    + "&token=" + MyApp.TOKEN
                    + "&market=" + JPushReceiver.F_MARKET;
5,传入post请求的参数
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            dos.writeBytes(params);
            dos.flush();
            dos.close();

6,获得响应状态,如果是ok的话,就代表响应成功。
            int resultCode = connection.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
		//成功后做一些操作
	    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值