Android學習之servlet登入、註冊實現
阿新 • • 發佈:2019-01-28
public class HttpLogin { public static String LoginByPost(String id,String password){ String address = "http://www.khqust.top/MyWebsite/androidlogin.do"; String result = ""; try{ URL url = new URL(address);//初始化URL HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//請求方式 //超時資訊 conn.setReadTimeout(5000); conn.setConnectTimeout(5000); //post方式不能設定快取,需手動設定為false conn.setUseCaches(false); //我們請求的資料 String data = "id="+ URLEncoder.encode(id,"UTF-8")+ "&password="+ URLEncoder.encode(password,"UTF-8"); //獲取輸出流 OutputStream out = conn.getOutputStream(); out.write(data.getBytes()); out.flush(); out.close(); conn.connect(); if (conn.getResponseCode() == 200) { // 獲取響應的輸入流物件 InputStream is = conn.getInputStream(); // 建立位元組輸出流物件 ByteArrayOutputStream message = new ByteArrayOutputStream(); // 定義讀取的長度 int len = 0; // 定義緩衝區 byte buffer[] = new byte[1024]; // 按照緩衝區的大小,迴圈讀取 while ((len = is.read(buffer)) != -1) { // 根據讀取的長度寫入到os物件中 message.write(buffer, 0, len); } // 釋放資源 is.close(); message.close(); // 返回字串 result = new String(message.toByteArray()); //return result; } }catch (MalformedURLException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return result; } public static String RegisterByPost(String id,String password,String email){ String address = "http://www.khqust.top/MyWebsite/androidregister.do"; String result = ""; try{ URL url = new URL(address);//初始化URL HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//請求方式 //超時資訊 conn.setReadTimeout(5000); conn.setConnectTimeout(5000); //post方式不能設定快取,需手動設定為false conn.setUseCaches(false); //我們請求的資料 String data = "id="+ URLEncoder.encode(id,"UTF-8")+ "&password="+ URLEncoder.encode(password,"UTF-8")+ "&email="+ URLEncoder.encode(email,"UTF-8"); //獲取輸出流 OutputStream out = conn.getOutputStream(); out.write(data.getBytes()); out.flush(); out.close(); conn.connect(); if (conn.getResponseCode() == 200) { // 獲取響應的輸入流物件 InputStream is = conn.getInputStream(); // 建立位元組輸出流物件 ByteArrayOutputStream message = new ByteArrayOutputStream(); // 定義讀取的長度 int len = 0; // 定義緩衝區 byte buffer[] = new byte[1024]; // 按照緩衝區的大小,迴圈讀取 while ((len = is.read(buffer)) != -1) { // 根據讀取的長度寫入到os物件中 message.write(buffer, 0, len); } // 釋放資源 is.close(); message.close(); // 返回字串 result = new String(message.toByteArray()); //return result; } }catch (MalformedURLException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return result; } }