博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android 之HttpURLConnection的post,get方式请求数据
阅读量:5267 次
发布时间:2019-06-14

本文共 7330 字,大约阅读时间需要 24 分钟。

get方式和post方式的区别:

1.请求的URL地址不同:

  post:"http://xx:8081//servlet/LoginServlet"
  get:http://xxx:8081//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://xx:8081");

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

    //设置UrlConnection可以写请求的内容

    openConnection.setDoOutput(true);
    //获取一个outputstream,并将内容写入该流
    openConnection.getOutputStream().write(body.getBytes());

3.请求时携带的内容大小不同

  get:1k
  post:理论无限制

 

登录的布局文件

登录的Activity代码

public class GetPostActivity extends AppCompatActivity {    private EditText et_username;    private EditText et_password;    private CheckBox cb_rem;    private Button bt_login;    private Context mcontext;    private String username;    private String password;    private boolean isRem;    @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();            }        });    }    //创建一个handler    Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            boolean isloginsuccess = (boolean) msg.obj;            if (isloginsuccess) {                //判断是否记住密码,要保存到本地,封装成方法                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();            }        }    };    public void login() {        username = et_username.getText().toString().trim();        password = et_password.getText().toString().trim();        isRem = cb_rem.isChecked();        //判断是否密码或者用户名为空        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();            return;        }        //post方法登录是否成功        LoginHttpUtil.requestNetForGetLogin(handler, username, password);    }}

 

新建一个Net包,处理网络请求的操作,新建一个loginhttputil.java

public class LoginHttpUtil {
//get方式登录 public static void requestNetForGetLogin(final Handler handler,final String username,final String password) {
//在子线程中操作网络请求 new Thread(new Runnable() {
@Override public void run() {
//urlConnection请求服务器,验证 try {
//1:url对象 URL url = new URL("http://192.168.1.100:8081//servlet/LoginServlet?username=" + URLEncoder.encode(username)+ "&pwd=" + URLEncoder.encode(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); boolean isLoginsuccess=false; if (result.contains("success")) {
isLoginsuccess=true; } Message msg = Message.obtain(); msg.obj=isLoginsuccess; handler.sendMessage(msg); } } catch (Exception e) {
e.printStackTrace(); } } }).start(); } //post方式登录 public static void requestNetForPOSTLogin(final Handler handler,final String username,final String password) {
new Thread(new Runnable() {
@Override public void run() {
//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=" + URLEncoder.encode(username) + "&pwd=" + URLEncoder.encode(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); boolean isLoginsuccess=false; if (result.contains("success")) {
isLoginsuccess=true; } Message msg = Message.obtain(); msg.obj=isLoginsuccess; handler.sendMessage(msg); } } catch (Exception e) {
e.printStackTrace(); } } }).start(); } }

 

 

二:get方式提交数据时候出现乱码的情况l;解决办法如下:

  一般在开发客户端和服务端的编码要保持一致。

    android端的默认编码是utf-8;

    做url请求时需要对参数进行URLEncode编码.

    URL url = new URL("http://xx:8081/servlet/LoginServlet?username="+URLEncoder.encode(username)+"&pwd="+URLEncoder.encode(password))

 

# 2.   post方式提交数据乱码解决

  

String body = "username=" + URLEncoder.encode(username) + "&pwd=" + URLEncoder.encode(password);

 

转载于:https://www.cnblogs.com/DonAndy/p/6195752.html

你可能感兴趣的文章
打飞机游戏【来源于Crossin的编程教室 http://chuansong.me/account/crossincode 】
查看>>
[LeetCode] Merge Intervals
查看>>
【翻译自mos文章】当点击完 finishbutton后,dbca 或者dbua hang住
查看>>
Linux编程简介——gcc
查看>>
2019年春季学期第四周作业
查看>>
MVC4.0 利用IActionFilter实现简单的后台操作日志功能
查看>>
windows下mongodb安装与使用
查看>>
rotate the clock
查看>>
bugku 变量
查看>>
Python 环境傻瓜式搭建 :Anaconda概述
查看>>
数据库01 /Mysql初识以及基本命令操作
查看>>
数据库02 /MySQL基础数据类型以及多表之间建立联系
查看>>
Python并发编程04/多线程
查看>>
CF461B Appleman and Tree
查看>>
CF219D Choosing Capital for Treeland
查看>>
杂七杂八的小笔记本
查看>>
51Nod1353 树
查看>>
CF1215E Marbles
查看>>
fish redux 个人理解
查看>>
BZOJ2339 HNOI2011卡农(动态规划+组合数学)
查看>>