今天研究了下原生請求網絡的形式
//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) {//成功后做一些操作}
新聞熱點
疑難解答