Android http HttpURLConnection

來源:互聯網
上載者:User

標籤:

 /**  * Http get 請求  *   * @param urlPath  *   *   */ private static String httpConnByGet(RequestUrl ru,Params params){   String token = (String) params.getMap().get("token") ;  String et = (String) params.getMap().get("et") ;  params.getMap().remove("et");  if(token != null ){   params.getMap().put("token",Md5.md5(token + et + params.getMap().get("uid") + ru.getKeywords()));  }    String urlPath = ru.getUrl() + HttpURLConstant.QMARK + HttpURLConstant.COMMON_PARAMS + et + params.toString() ; //通用參數的設定  Log.w("NETURL","geturl:"+urlPath);  URL url = null;  HttpURLConnection urlConnection = null;      try {   ByteArrayOutputStream outStream = new ByteArrayOutputStream();   byte[] data = new byte[2048];    //應該不會小吧!   int len = 0;   url = new URL(urlPath);      urlConnection = (HttpURLConnection) url.openConnection();     //   Class<?> clazz=url.openConnection().getClass();  //看看返回什麼鬼類型//   Class<?> clazzSuper=clazz.getSuperclass();       //父類又是什麼鬼啊!         //getInputStream暗中執行了串連,不需要urlConnection.connect();   urlConnection.setReadTimeout(readTimeout);                                                  // 佈建要求的逾時時間   urlConnection.setConnectTimeout(connectTimeout);   if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {         InputStream inStream = urlConnection.getInputStream();   //擷取輸入資料流,此時才真正建立連結    while ((len = inStream.read(data)) != -1) {     outStream.write(data, 0, len);    }        inStream.close();       if(isDebug){Log.e(TAG,"get 返回資料"+new String(outStream.toByteArray()));}    return new String(outStream.toByteArray());   }else{ //返回的是HTTP的錯誤碼,不是我們自己定義的錯誤碼!        //處理一下http的錯誤返回碼            Log.e(TAG,"get 網路連接失敗"+urlConnection.getResponseCode());    return "HTTP_ERROR-"+urlConnection.getResponseCode();   }  } catch (MalformedURLException e) {   e.printStackTrace();   Log.e(TAG,"MalformedURLException e");  } catch (IOException e) {   e.printStackTrace();   Log.e(TAG,"IOException e");  } finally{          if(urlConnection!=null){    urlConnection.disconnect();  //總是需要關閉的吧!   }     }  return null;   }              /**  * Http Post 請求  *  * @param urlpath  * @param paramsDatas  */ private static String httpConnByPost(RequestUrl ru,Params params) {  String token = (String) params.getMap().get("token") ;  String et = (String) params.getMap().get("et") ;  params.getMap().remove("et");  if(token != null ){   params.getMap().put("token", Md5.md5(token + et + params.getMap().get("uid") + ru.getKeywords()));  }    URL url = null;                                                       // 根據地址建立URL對象  HttpURLConnection urlConnection = null;                               // 根據URL對象開啟連結  try {   url = new URL(ru.getUrl());                                                          // 根據地址建立URL對象   urlConnection = (HttpURLConnection) url.openConnection();                            // 根據URL對象開啟連結      urlConnection.setRequestMethod("POST");                                               // 佈建要求的方式   urlConnection.setReadTimeout(readTimeout);                                            // 佈建要求的逾時時間   urlConnection.setConnectTimeout(connectTimeout);         String paramsData = HttpURLConstant.COMMON_PARAMS + et + params.toString();           //通用參數的使用要注意   Log.w("NETURL",url+"?"+paramsData);      urlConnection.setRequestProperty("Connection", "keep-alive");                         // 設定維持長串連     urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 設定檔案的類型   urlConnection.setRequestProperty("Content-Length",String.valueOf(paramsData.getBytes().length)); // 設定資料的長度   urlConnection.setRequestProperty("User-Agent","Devond_Watch,Android-device.");  // ???   urlConnection.setDoOutput(true);   // 發送POST請求必須設定允許輸出   urlConnection.setDoInput(true);    // 發送POST請求必須設定允許輸入,setDoInput的預設值就是true   urlConnection.setUseCaches(false); // 為安全,不允許使用緩衝         urlConnection.connect();           //urlConnection.getInputStream()的時候會自動的開啟串連的   OutputStream os = urlConnection.getOutputStream();    //擷取輸出資料流developer   os.write(paramsData.getBytes());   os.flush();      if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {                     InputStream is = urlConnection.getInputStream();          // 擷取響應的輸入資料流對象    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 建立位元組輸出資料流對象    int len = 0;                                              // 定義讀取的長度    byte buffer[] = new byte[2048];                           // 定義緩衝區    while ((len = is.read(buffer)) != -1) {                   // 按照緩衝區的大小,迴圈讀取     baos.write(buffer, 0, len);                           // 根據讀取的長度寫入到os對象中    }    is.close();// 釋放資源       baos.close();      final String result = new String(baos.toByteArray());        if(isDebug){     Log.e(TAG,"Post返回的資料:"+result);    }     return new String(baos.toByteArray());       }else{ //返回的是HTTP的錯誤碼,不是我們自己定義的錯誤碼!    //處理一下http的錯誤返回碼    Log.e(TAG,urlConnection.getResponseCode()+"#Post 網路連接失敗#"+urlConnection.getErrorStream());    return "HTTP_ERROR-"+urlConnection.getResponseCode();   }  } catch (MalformedURLException e) {   e.printStackTrace();   Log.e(TAG,"MalformedURLException e");  }catch (Exception e) {   e.printStackTrace();  }finally{      if(urlConnection!=null){    urlConnection.disconnect();   }     }  Log.e(TAG,"Post 請求返回為空白");  return null; }

 

Android http HttpURLConnection

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.