zoukankan      html  css  js  c++  java
  • 提交数据到服务器

    一、通过POST和GET两种方式分别向服务器提交数据

    package com.shz.services;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    
    public class loginService {
    
        /**
         * 通过GET请求方式向服务器提交数据
         * 
         * @param userName
         * @param password
         * @return
         */
        public static String loginByGet(String userName, String password) {
            try {
                String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login?UserName="
                        + URLEncoder.encode(userName)
                        + "&Password="
                        + URLEncoder.encode(password);
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(5000);
                conn.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
                int code = conn.getResponseCode();
                if (code == 200) {
                    return readInputStream(conn.getInputStream());
                } else {
                    return "请求失败,错误码:" + code;
                }
    
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    
        /**
         * 通过POST请求方式向服务器提交数据
         * 
         * @param userName
         * @param password
         * @return
         */
        public static String loginByPost(String userName, String password) {
            try {
                String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login";
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setReadTimeout(5000);
                conn.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                String data = "UserName=" + URLEncoder.encode(userName)
                        + "&Password=" + URLEncoder.encode(password); // 需要Post的数据
                conn.setRequestProperty("Content-Length",
                        String.valueOf(data.length()));
    
                OutputStream os = conn.getOutputStream();
                os.write(data.getBytes());
    
                int code = conn.getResponseCode();
                if (code == 200) {
                    return readInputStream(conn.getInputStream());
                } else {
                    return "请求失败,错误码:" + code;
                }
    
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    
        /**
         * 通过HttpClient GET请求方式向服务器提交数据
         * 
         * @param userName
         * @param password
         * @return
         */
        public static String loginByHttpClientGet(String userName, String password) {
            try {
                // 1.打开浏览器
                HttpClient httpClient = new DefaultHttpClient();
                // 2.输入URL地址
                String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login?UserName="
                        + URLEncoder.encode(userName)
                        + "&Password="
                        + URLEncoder.encode(password);
                HttpGet httpGet = new HttpGet(path);
                // 3.敲回车
                HttpResponse response = httpClient.execute(httpGet);
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    InputStream is = response.getEntity().getContent();
                    return readInputStream(is);
                } else {
                    return "请求失败,错误码:" + code;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "请求异常:" + e.getMessage();
            }
        }
    
        /**
         * 通过HttpClient Post 请求方式向服务器提交数据
         * 
         * @param userName
         * @param password
         * @return
         */
        public static String loginByHttpClientPost(String userName, String password) {
            try {
                // 1.打开浏览器
                HttpClient httpClient = new DefaultHttpClient();
                // 2.输入URL地址
                String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login";
                HttpPost httpPost = new HttpPost(path);
                // 设置要提交的数据
                List<NameValuePair> data = new ArrayList<NameValuePair>();
                data.add(new BasicNameValuePair("UserName", userName));
                data.add(new BasicNameValuePair("Password", password));
                httpPost.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
    
                // 3.敲回车
                HttpResponse response = httpClient.execute(httpPost);
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    InputStream is = response.getEntity().getContent();
                    return readInputStream(is);
                } else {
                    return "请求失败,错误码:" + code;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "请求异常:" + e.getMessage();
            }
        }
    
        public static String readInputStream(InputStream is) {
            try {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                int length = 0;
                byte[] buffer = new byte[1024];
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
    
                is.close();
                os.close();
    
                byte[] osByte = os.toByteArray();
                return new String(osByte);
            } catch (Exception e) {
                e.printStackTrace();
                return "读取输入流异常";
            }
        }
    }

    二、服务器端代码(Asp.Net MVC)

    public ActionResult Login()
            {
                string username = Request["UserName"];
                string password = Request["Password"];
                string msg = "";
    
                if(username.Equals("admin") && password.Equals("123"))
                {
                    msg = "(GET)登录成功!";
                }
                else
                {
                    msg = "(GET)无效的用户名或密码!";
                }
    
                return Content(msg);
            }
    
            [HttpPost]
            public ActionResult Login(FormCollection collection)
            {
                string username = Request["UserName"];
                string password = Request["Password"];
                string msg = "";
    
                if (username.Equals("admin") && password.Equals("123"))
                {
                    msg = "(POST)登录成功!";
                }
                else
                {
                    msg = "(POST)无效的用户名或密码!";
                }
    
                return Content(msg);
            }

    三、客户端代码(布局+UI逻辑)

    package com.shz.login;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.view.View;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import com.shz.loginServer.R;
    import com.shz.services.loginService;
    
    public class MainActivity extends Activity {
    
        private EditText txtUserName;
        private EditText txtPassword;
        private CheckBox cbRememberPwd;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            this.txtUserName = (EditText)this.findViewById(R.id.txtUserName);
            this.txtPassword = (EditText)this.findViewById(R.id.txtPassword);
            this.cbRememberPwd = (CheckBox)this.findViewById(R.id.cbRememberPwd);
            
            
        }        
        
        public void loginGet(View view)
        {
            final String userName = this.txtUserName.getText().toString().trim();
            final String password = this.txtPassword.getText().toString().trim();
            
            if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
            {
                Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
                return;
            }
            
            new Thread(){
                public void run() {
                    final String result = loginService.loginByGet(userName, password);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                        }
                    });
                };
            }.start();
        }    
        
        public void loginPost(View view)
        {
            final String userName = this.txtUserName.getText().toString().trim();
            final String password = this.txtPassword.getText().toString().trim();
            
            if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
            {
                Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
                return;
            }
            
            new Thread(){
                public void run() {
                    final String result = loginService.loginByPost(userName, password);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                        }
                    });
                };
            }.start();
        }  
    
    }
    View Code
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.shz.login.MainActivity"
        tools:ignore="MergeRootFrame" >
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/please_input_username" />
    
        <EditText
            android:id="@+id/txtUserName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="none" />
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/please_input_password" />
    
        <EditText
            android:id="@+id/txtPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword" />
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
    
            <CheckBox
                android:id="@+id/cbRememberPwd"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:checked="true"
                android:text="@string/remember_password" />
    
            <Button
                android:id="@+id/btnLoginGet"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/cbRememberPwd"
                android:layout_alignParentLeft="true"
                android:onClick="loginGet"
                android:text="@string/btn_loginGet" />
            
            <Button
                android:id="@+id/btnLoginPost"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/cbRememberPwd"
                android:layout_alignParentRight="true"
                android:onClick="loginPost"
                android:text="@string/btn_loginPost" />
        </RelativeLayout>
    
    </LinearLayout>
    View Code

    四、效果图

  • 相关阅读:
    eWebEditor在ie9下按钮功能失效的解决办法
    FLV视频播放代码
    笔记 PHP常用 语句
    jquery 无刷新加载执行,显示数据
    常用的PHP与SQL语句
    PHP常用语句
    Ajax+php 无刷新更新数据.并将数据库操作改写成类.
    js下拉框联动代码
    PHP 更新功能 笔记
    MyEclipse8.5开发环境配置中SVN插件安装重点解析
  • 原文地址:https://www.cnblogs.com/shaomenghao/p/3920689.html
Copyright © 2011-2022 走看看