5.1提交數據到服務器

有兩種方法,post跟get方法:post不需要帶參,get可以直接在網址後帶參請求。
post:

/**
     * 使用post的方式登錄
     * @param userName
     * @param password
     * @return
     */
    public static String loginOfPost(String userName, String password) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet");

            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10000); // 連接的超時時間
            conn.setReadTimeout(5000); // 讀數據的超時時間
            conn.setDoOutput(true); // 必須設置此方法, 允許輸出
//          conn.setRequestProperty("Content-Length", 234);     // 設置請求頭消息, 可以設置多個

            // post請求的參數
            String data = "username=" + userName + "&password=" + password;

            // 獲得一個輸出流, 用於向服務器寫數據, 默認情況下, 系統不允許向服務器輸出內容
            OutputStream out = conn.getOutputStream();  
            out.write(data.getBytes());
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();
            if(responseCode == 200) {
                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
                Log.i(TAG, "訪問失敗: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

get:

/**
     * 使用get的方式登錄
     * @param userName
     * @param password
     * @return 登錄的狀態
     */
    public static String loginOfGet(String userName, String password) {
        HttpURLConnection conn = null;
        try {
            //10.0.2.2手機上的pc平臺服務器地址
            String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
            URL url = new URL("http://10.0.2.2:8080/Server/servlet/LoginServlet?" + data);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");       // get或者post必須得全大寫
            conn.setConnectTimeout(10000); // 連接的超時時間
            conn.setReadTimeout(5000); // 讀數據的超時時間

            int responseCode = conn.getResponseCode();
            if(responseCode == 200) {
                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
                Log.i(TAG, "訪問失敗: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                conn.disconnect();      // 關閉連接
            }
        }
        return null;
    }

Main函數中的方法使用:

public void doGet(View v) {
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();

        new Thread(
                new Runnable() {

                    @Override
                    public void run() {
                        // 使用get方式抓去數據
                        final String state = NetUtils.loginOfGet(userName, password);

                        // 執行任務在主線程中
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 就是在主線程中操作
                                Toast.makeText(MainActivity.this, state, 0).show();
                            }
                        });
                    }
                }).start();
    }

    public void doPost(View v) {
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final String state = NetUtils.loginOfPost(userName, password);
                // 執行任務在主線程中
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 就是在主線程中操作
                        Toast.makeText(MainActivity.this, state, 0).show();
                    }
                });
            }
        }).start();
    }

根據流返回一個字符串信息:

/**
     * 根據流返回一個字符串信息
     * @param is
     * @return
     * @throws IOException 
     */
    private static String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;

        while((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        is.close();

        String html = baos.toString();  // 把流中的數據轉換成字符串, 採用的編碼是: utf-8

//      String html = new String(baos.toByteArray(), "GBK");

        baos.close();
        return html;
    }
發佈了50 篇原創文章 · 獲贊 14 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章