今天研究了下原生请求网络的形式
//1,new 一个线程new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try {2,请求的地址:如 http:www.baidu.comURL 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) {//成功后做一些操作}
新闻热点
疑难解答