Android 採用post方式提交資料到伺服器,androidpost

來源:互聯網
上載者:User

Android 採用post方式提交資料到伺服器,androidpost

接著上篇《Android 採用get方式提交資料到伺服器》,本文來實現採用post方式提交資料到伺服器

首先對比一下get方式和post方式: 

修改布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <EditText        android:id="@+id/et_name"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="請輸入使用者名稱"        android:inputType="text" />    <EditText        android:id="@+id/et_pwd"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="請輸入密碼"        android:inputType="textPassword" />    <Button         android:onClick="LoginByGet"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="GET方式登入"        />     <Button         android:onClick="LoginByPost"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="POST方式登入"        /></LinearLayout>

添加代碼:

package com.wuyudong.loginclient;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import android.os.Build;import android.os.Bundle;import android.os.StrictMode;import android.annotation.SuppressLint;import android.annotation.TargetApi;import android.app.Activity;import android.text.TextUtils;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {    private EditText et_name;    private EditText et_pwd;    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        et_name = (EditText) findViewById(R.id.et_name);        et_pwd = (EditText) findViewById(R.id.et_pwd);        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()                .permitAll().build();        StrictMode.setThreadPolicy(policy);    }    public void LoginByGet(View view) {        String name = et_name.getText().toString().trim();        String pwd = et_pwd.getText().toString().trim();        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {            Toast.makeText(this, "使用者名稱密碼不可為空", 0).show();        } else {            // 類比http請求,提交資料到伺服器            String path = "http://169.254.168.71:8080/web/LoginServlet?username="                    + name + "&password=" + pwd;            try {                URL url = new URL(path);                // 2.建立一個http串連                HttpURLConnection conn = (HttpURLConnection) url                        .openConnection();                // 3.設定一些請求方式                conn.setRequestMethod("GET");// 注意GET單詞字幕一定要大寫                conn.setRequestProperty(                        "User-Agent",                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");                int code = conn.getResponseCode(); // 伺服器的響應碼 200 OK //404 頁面找不到                                                    // // 503伺服器內部錯誤                if (code == 200) {                    InputStream is = conn.getInputStream();                    // 把is的內容轉換為字串                    ByteArrayOutputStream bos = new ByteArrayOutputStream();                    byte[] buffer = new byte[1024];                    int len = -1;                    while ((len = is.read(buffer)) != -1) {                        bos.write(buffer, 0, len);                    }                    String result = new String(bos.toByteArray());                    is.close();                    Toast.makeText(this, result, 0).show();                } else {                    Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show();                }            } catch (Exception e) {                e.printStackTrace();                Toast.makeText(this, "請求失敗,請檢查logcat日誌控制台", 0).show();            }        }    }    /**     * 採用post的方式提交資料到伺服器     *      * @param view     */    public void LoginByPost(View view) {        String name = et_name.getText().toString().trim();        String pwd = et_pwd.getText().toString().trim();        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {            Toast.makeText(this, "使用者名稱密碼不可為空", 0).show();        } else {            try {                String path = "http://169.254.168.71:8080/web/LoginServlet?username="                        + name + "&password=" + pwd;                // 1.定義請求url                URL url = new URL(path);                // 2.建立一個http的串連                HttpURLConnection conn = (HttpURLConnection) url                        .openConnection();                // 3.設定一些請求的參數                conn.setRequestMethod("POST");                conn.setRequestProperty(                        "User-Agent",                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");                conn.setRequestProperty("Content-Type",                        "application/x-www-form-urlencoded");                String data = "username=" + name + "&password=" + pwd;                conn.setRequestProperty("Content-Length", data.length() + "");                conn.setConnectTimeout(5000);//設定連線逾時時間                conn.setReadTimeout(5000); //設定讀取的逾時時間                                // 4.一定要記得設定 把資料以流的方式寫給伺服器                conn.setDoOutput(true); // 設定要向伺服器寫資料                conn.getOutputStream().write(data.getBytes());                int code = conn.getResponseCode(); // 伺服器的響應碼 200 OK //404 頁面找不到                // // 503伺服器內部錯誤                if (code == 200) {                    InputStream is = conn.getInputStream();                    // 把is的內容轉換為字串                    ByteArrayOutputStream bos = new ByteArrayOutputStream();                    byte[] buffer = new byte[1024];                    int len = -1;                    while ((len = is.read(buffer)) != -1) {                        bos.write(buffer, 0, len);                    }                    String result = new String(bos.toByteArray());                    is.close();                    Toast.makeText(this, result, 0).show();                } else {                    Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show();                }            } catch (Exception e) {                e.printStackTrace();                Toast.makeText(this, "請求失敗,請檢查logcat日誌控制台", 0).show();            }        }    }}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.