码迷,mamicode.com
首页 > 移动开发 > 详细

android 之post,get方式请求数据

时间:2016-12-18 23:54:53      阅读:418      评论:0      收藏:0      [点我收藏+]

标签:userinfo   success   put   open   void   line   不同   cal   wrap   

get方式和post方式的区别:

1.请求的URL地址不同:
  post:"http://xx:8080//servlet/LoginServlet"
  get:http://xxx:8080//servlet/LoginServlet?username=root&pwd=123

2.请求头不同:
  ****post方式多了几个请求头:Content-Length   ,   Cache-Control , Origin

    openConnection.setRequestProperty("Content-Length", body.length()+"");
    openConnection.setRequestProperty("Cache-Control", "max-age=0");
    openConnection.setRequestProperty("Origin", "http://192.168.13.83:8080");

  ****post方式还多了请求的内容:username=root&pwd=123

    //设置UrlConnection可以写请求的内容
    openConnection.setDoOutput(true);
    //获取一个outputstream,并将内容写入该流
    openConnection.getOutputStream().write(body.getBytes());

3.请求时携带的内容大小不同
  get:1k
  post:理论无限制

 

 

登录的布局文件

<?xml version="1.0" encoding="utf-8"?>
<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="com.example.yb.myapplication.MainActivity">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/input_username"
        android:hint="@string/input_username"/>

    <EditText
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:inputType="textPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/input_password"
        android:hint="@string/input_password"/>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:layout_marginLeft="30dp"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/cb_rem"
            android:text="@string/reme_password"/>

        <Button
            android:layout_marginRight="30dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:layout_alignParentRight="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/bt_login"
            android:text="@string/bt_login"/>
    </RelativeLayout>
</LinearLayout>

登录的Activity代码

    private EditText et_username;
    private EditText et_password;
    private CheckBox cb_rem;
    private Button bt_login;
    private Context mcontext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_post);

        et_username = (EditText) findViewById(R.id.input_username);
        et_password = (EditText) findViewById(R.id.input_password);
        cb_rem = (CheckBox) findViewById(R.id.cb_rem);
        bt_login = (Button) findViewById(R.id.bt_login);
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });

        //界面加载完回显密码和用户名,读取文件,回显,用户名和密码的封装可以是:数组封装,Map封装,bean封装,
       /* Map<String, String> map = UserInfoUtil.getUserInfo(mcontext);
        if (map != null) {
            String username = map.get("username");
            String password = map.get("password");
            et_username.setText(username);
            et_password.setText(password);
            cb_rem.setChecked(true);
        }*/

    }

    public void login() {

        final String username = et_username.getText().toString().trim();
        final String password = et_password.getText().toString().trim();
        final boolean isRem = cb_rem.isChecked();
        //判断是否密码或者用户名为空
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        //子线程操作,子线程不能做 更新U I
        new Thread(new Runnable() {
            @Override
            public void run() {
                //get方法登录是否成功
               // final boolean b = requestNetForGetLogin(username, password);
                final boolean b = requestNetForPOSTLogin(username, password);
                System.out.println("=====================是否登录成功:" + b);

                runOnUiThread(new Runnable() {  //直接用acitivty类的runOnUiThread(runnable run)方法,可以在子线程中更新UI
                    @Override
                    public void run() {
                        //运行在主线程里了
                        if (b) {
                            //判断是否记住密码,要保存到本地,封装成方法
                            if (isRem) {
                                //保存用户名和密码
                                boolean result = UserInfoUtil.saveUserInfo(mcontext, username, password);
                                if (result) {
                                    Toast.makeText(getApplicationContext(), "用户名和密码保存成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(getApplicationContext(), "用户名和密码保存失败", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        }).start();
        //请求服务器
    }

    //get方式登录
    private boolean requestNetForGetLogin(String username, String password) {
        //urlConnection请求服务器,验证
        try {
            //1:url对象
            URL url = new URL("http://192.168.1.100:8081/servlet/LoginServlet?username=" + username + "&pwd=" + password + "");

            //2;url.openconnection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //3
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            //4
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream inputStream = conn.getInputStream();
                String result = StreamUtil.stremToString(inputStream);
                System.out.println("=====================服务器返回的信息::" + result);
                if (result.contains("success")) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    //post方式登录
    private boolean requestNetForPOSTLogin(String username, String password) {
        //urlConnection请求服务器,验证
        try {
            //1:url对象
            URL url = new URL("http://192.168.1.100:8081//servlet/LoginServlet");

            //2;url.openconnection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //3设置请求参数
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10 * 1000);
        //请求头的信息
            String body="username="+username+"&pwd="+password;
            conn.setRequestProperty("Content-Length", String.valueOf(body.length()));
            conn.setRequestProperty("Cache-Control","max-age=0");
            conn.setRequestProperty("Origin","http://192.168.1.100:8081");

            //设置conn可以写请求的内容
            conn.setDoOutput(true);
            conn.getOutputStream().write(body.getBytes());

            //4响应码
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream inputStream = conn.getInputStream();
                String result = StreamUtil.stremToString(inputStream);
                System.out.println("=====================服务器返回的信息::" + result);
                if (result.contains("success")) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

新建一个工具包Util, 新建一个类UserInfoUtil 

public class UserInfoUtil {
    public static boolean saveUserInfo(Context context, String username, String password) {
        //需要使用shrare10.sharedPreference的使用
        try {

            //1使用Context创建一个SharePerference对象
            SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);

            //2SharePerference对象得到Editor对象
            Editor edit = sharedPreferences.edit();

            //3往Editor对象里面添加数据
            edit.putString("username",username);
            edit.putString("password",password);

            //4提交Editor对象
            edit.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    //用户名和密码的封装可以是:数组封装,Map封装,bean封装,这里采用map封装
    public static Map<String, String> getUserInfo(Context context) {
        try {
            //1 使用Context创建一个SharePerference对象
            SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);

            //2SharePerference对象获取存放的数据
            String username = sharedPreferences.getString("username", "");
            String password = sharedPreferences.getString("password", "");

            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("username", username);
            hashMap.put("password", password);
            return hashMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

新建工具类StreamUtil,获取的读取流转为String返回

public class StreamUtil {
    /**
     * 获取的读取流转为String返回
     *
     * @param inputStream
     */
    public static String stremToString(InputStream in) {
        String result="";
        try {
            //创建一个字节数组写入流
            ByteArrayOutputStream out=new ByteArrayOutputStream();

            byte[] buffer=new byte[1024];
            int length=0;
            while((length=in.read(buffer))!=-1){  //如果返回-1 则表示数据读取完成了。
                out.write(buffer,0,length);//写入数据
                out.flush();
            }
            result=out.toString();//写入流转为字符串
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

android 之post,get方式请求数据

标签:userinfo   success   put   open   void   line   不同   cal   wrap   

原文地址:http://www.cnblogs.com/DonAndy/p/6195752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!