zoukankan      html  css  js  c++  java
  • Android 使用HTTP(get和post)方式登陆服务器

    package com.wuyou.submittoserver;
    
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.text.TextUtils;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    
    public class MainActivity extends ActionBarActivity {
    
        private static final int OK = 200;
        private EditText usernameEditText;
        private EditText passwrodEditText;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            usernameEditText = (EditText) findViewById(R.id.username);
            passwrodEditText = (EditText) findViewById(R.id.password);
        }
    
        /**
         * post方法多了三个东西:
         * ①请求的表单类型
         * ②请求的数据长度
         * ③请求的数据并且写给服务器
         */
        public void post(View view) {
            final String username = usernameEditText.getText().toString().trim();
            final String password = passwrodEditText.getText().toString().trim();
            //Android默认模拟器外部的地址为10.0.2.2,而不是localhost和127.0.0.1
            final String serverPath = "http://10.0.2.2:8080/LoginServlet";
            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                //给出提示:账号密码不许为空
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //向服务器请求的数据
                            String data = "username=" + URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
                            URL url = new URL(serverPath);
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                            httpURLConnection.setRequestMethod("POST");
                            httpURLConnection.setConnectTimeout(3000);
                            httpURLConnection.setDoOutput(true);//打开输出流,以便向服务器提交数据
                            //设置请求体的类型是文本类型
                            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            //设置请求体的长度
                            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length()));
                            //获得输出流,向服务器写入数据
                            OutputStream outputStream = httpURLConnection.getOutputStream();
                            outputStream.write(data.getBytes());
    
                            int responseCode = httpURLConnection.getResponseCode();
                            if (200 == responseCode) {
                                InputStream inputStream = httpURLConnection.getInputStream();
                                final String responseMsg = StreamTool.getString(inputStream);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, responseMsg, Toast.LENGTH_LONG).show();
                                    }
                                });
                            } else {
                                System.out.println("responseCode = " + responseCode);
                                //连接服务器出错,错误代码为:responseCode 根据代码值告诉用户出错的原因
                                //....
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    
        public void get(View view) {
            final String username = usernameEditText.getText().toString().trim();
            final String password = passwrodEditText.getText().toString().trim();
            //Android默认模拟器外部的地址为10.0.2.2,而不是localhost和127.0.0.1
            final String serverPath = "http://10.0.2.2:8080/LoginServlet";
            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                //给出提示:账号密码不许为空
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //使用GET方式请求服务器只能这样
                            URL url = new URL(serverPath + "?username=" + URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8"));
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                            httpURLConnection.setRequestMethod("GET");
                            httpURLConnection.setConnectTimeout(5000);
                            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0");
                            int responseCode = httpURLConnection.getResponseCode();
                            if (200 == responseCode) {
                                InputStream inputStream = httpURLConnection.getInputStream();
                                final String responseMsg = StreamTool.getString(inputStream);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, responseMsg, Toast.LENGTH_LONG).show();
                                    }
                                });
                            } else {
                                System.out.println("responseCode = " + responseCode);
                                //连接服务器出错,错误代码为:responseCode 根据代码值告诉用户出错的原因
                                //....
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }
    
    class StreamTool {
        public static String getString(InputStream inputStream) throws IOException {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int length;
            while((length = inputStream.read(buf)) >0) {
                byteArrayOutputStream.write(buf, 0 ,length);
            }
            byte[] stringBytes = byteArrayOutputStream.toByteArray();
            String str = new String(stringBytes);
            return str;
        }
    }

    界面就不写了。

    要注意几个地方:

    ①模拟器访问本机服务器127.0.01(locahost)的话,使用的地址是:10.0.2.2

    ②post比get方法多了三个要发送的数据头(header)

  • 相关阅读:
    学Maven,这篇万余字的教程,真的够用了!
    15 个优秀开源的 Spring Boot 学习项目,一网打尽!
    Spring Boot2 系列教程(三十)Spring Boot 整合 Ehcache
    800java面试题
    Nginx开发从入门到精通
    曹工说mini-dubbo(1)--为了实践动态代理,我写了个简单的rpc框架
    redis好书推荐
    一步一步学solr--windows下solr5.4.0环境搭建
    Redis
    8 个最好的 jQuery 树形 Tree 插件
  • 原文地址:https://www.cnblogs.com/wuyou/p/3427572.html
Copyright © 2011-2022 走看看