手動get post請求網路(面向http協議向伺服器提交資料)
阿新 • • 發佈:2018-12-31
private void requestNetWorkGet() { try { //把要提交的資料放在url裡,accounts pwd為使用者輸入 String path = "http://192.168.1.100:8080/web/LoginServer" + "?accounts = " + accounts + "&pwd = " + pwd; //建立一個Url URL url = new URL(path); //用url開啟連線 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //設定請求引數 conn.setRequestMethod("GET"); conn.setReadTimeout(3000); conn.setConnectTimeout(3000); //獲取狀態碼 int code = conn.getResponseCode(); //* 2xxx成功 3xxx重定向 4xxx資源錯誤 5xxx伺服器錯誤 if (code == 200) { //獲取伺服器返回的輸入流 InputStream is = conn.getInputStream(); //將溜流轉換成字串 String text = StreamUtils.parseStream(is); //拿到這個text可以在子執行緒中用Toast彈出來,用來測試請求成功與否 這裡我就不繼續做了 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }public static String parseStream(InputStream is) { try { //記憶體輸出流 效率高 ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int len = -1; //讀取流 while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } //拿到二進位制的資料 byte[] byteArray = baos.toByteArray(); //預設的編碼還是utf-8 return new String(byteArray); } catch (Exception e) { e.printStackTrace(); return null; } }