首页 > 学院 > 开发设计 > 正文

原生HttpUrlConnection

2019-11-06 09:43:08
字体:
来源:转载
供稿:网友

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

//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) {
		//成功后做一些操作
	    }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表