Android-HttpURLConnection-Get与Post请求登录功能
HttpURLConnection 在这请求方式是Java包中的;
AndroidManifest.xml配置权限:
<!-- 访问网络是危险的行为 所以需要权限 -->
<uses-permission android:name="android.permission.INTERNET" /> <!-- 设置壁纸是危险的行为 所以需要权限 -->
<uses-permission android:name="android.permission.SET_WALLPAPER" />
MainActivity7.java :
package liudeli.async; import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map; public class MainActivity7 extends Activity implements View.OnClickListener { private EditText etName;
private EditText etPwd;
private Button btLogin; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7); etName = findViewById(R.id.et_name);
etPwd = findViewById(R.id.et_pwd);
btLogin = findViewById(R.id.bt_login); btLogin.setOnClickListener(this);
} // 请求服务器的地址
private final String PATH = "http://127.0.0.1:8080/LoginServlet"; @Override
public void onClick(View v) {
// 拼装参数
final Map<String, String> map = new HashMap<>();
map.put("name", etName.getText().toString());
map.put("pwd", etPwd.getText().toString()); // 联网操作必须开启线程,执行异步任务
new Thread(){ @Override
public void run() {
super.run(); try { // Get请求方式,参数操作是拼接在链接
loginByGet(PATH, map); // Post请求方式,参数操作是封装实体对象
loginByPost(PATH, map); } catch (Exception e) {
e.printStackTrace();
threadRunToToast("登录是程序发生异常");
}
} }.start();
} /**
* HttpURLConnection Get 方式请求
* @param path 请求的路径
* @param map 请求的参数
* 拼接后的完整路径:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456
*/
private void loginByGet(String path, Map<String, String> map) throws Exception{
// 拼接路径地址 拼接后的完整路径:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456
StringBuffer pathString = new StringBuffer(path);
pathString.append("?"); // 迭代遍历Map
for (Map.Entry<String, String> mapItem : map.entrySet()) {
String key = mapItem.getKey();
String value = mapItem.getValue(); // name=zhangsan&
pathString.append(key).append("=").append(value).append("&");
}
// name=zhangsan&pwd=123456& 删除最后一个符号& 删除后:name=zhangsan&pwd=123456
pathString.deleteCharAt(pathString.length() - 1);
// 最后完整路径地址是:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456 // 第一步 包装网络地址
URL url = new URL(pathString.toString()); // 第二步 打开连接对象
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // 第三步 设置连接超时时长
httpURLConnection.setConnectTimeout(5000); // 第四步 设置请求方式Get
httpURLConnection.setRequestMethod("GET"); // 第五步 发生请求 ⚠注意:只有在>>httpURLConnection.getResponseCode(); 才向服务器发请求
int responseCode = httpURLConnection.getResponseCode(); // 第六步 判断请求码是否成功
// 注意⚠️:只有在执行conn.getResponseCode() 的时候才开始向服务器发送请求
if(responseCode == HttpURLConnection.HTTP_OK) { // 第七步 获取服务器响应的流
InputStream inputStream = httpURLConnection.getInputStream(); byte[] bytes = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (-1 != (len = inputStream.read())) {
// 把存取到bytes的数据,写入到>>ByteArrayOutputStream
bos.write(bytes, 0, len);
} // 第六步 判断是否请求成功, 注意:⚠️ success 是自定义服务器返回的 success代表登录成功
String loginResult = bos.toString();
if ("success".equals(loginResult)) { // 不能子在子线程中Toast
// Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show(); threadRunToToast("登录成功"); } else {
// 不能子在子线程中Toast
// Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show(); threadRunToToast("登录失败");
} // 第七步 关闭流
inputStream.close();
bos.close(); } else {
// 不能子在子线程中Toast
// Toast.makeText(this, "登录失败,请检查网络!", Toast.LENGTH_SHORT).show();
threadRunToToast("登录失败,请检查网络!");
}
} /**
* HttpURLConnection Get 方式请求
* @param path 请求的路径
* @param params 请求的参数
* 路径:http://127.0.0.1:8080/LoginServlet
*
* 参数:
* name=zhangsan
* pwd=123456
*/
private void loginByPost(String path, Map<String, String> params) throws Exception { // ------------------------------------------------ 以下是实体拼接帮助 /**
* 拼实体 注意⚠️:是需要服务器怎么配置 这里就要怎么拼接 例如:user.name=zhangsan&user.pwd=123
* 注意:⚠ 这不是访问服务器的地址,这是拼接实体
*/
StringBuilder paramsString = new StringBuilder();
for(Map.Entry<String, String> entry: params.entrySet()){
paramsString.append(entry.getKey());
paramsString.append("=");
paramsString.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
paramsString.append("&");
}
/**
* user.name=zhangsan&user.pwd=123& 删除最后一个符号& 删除后:user.name=zhangsan&user.pwd=123
* 注意:⚠ 这不是访问服务器的地址,这是拼接实体
*/
paramsString.deleteCharAt(paramsString.length() - 1); // 理解为实体
byte[] entity = paramsString.toString().getBytes(); // ------------------------------------------------ 以下是 HttpURLConnection Post 访问 代码 // 第一步 包装网络地址
URL url = new URL(path); // 第二步 打开连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 第三步 设置连接超时时长
conn.setConnectTimeout(5000); // 第四步 设置请求方式 POST
conn.setRequestMethod("POST"); /**
* 第五步 设置请求参数
* 请求参数类型
*/
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 请求实体的长度(字节)
conn.setRequestProperty("Content-Length", entity.length+""); // 第六步 允许对外输出
conn.setDoOutput(true); // 第七步 得到输出流 并把实体输出写出去
OutputStream os = conn.getOutputStream();
os.write(entity); // 注意⚠️:只有在执行conn.getResponseCode() 的时候才开始向服务器发送请求
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){ // 第八步 获取服务器响应的流
InputStream inputStream = conn.getInputStream(); byte[] bytes = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (-1 != (len = inputStream.read())) {
// 把存取到bytes的数据,写入到>>ByteArrayOutputStream
bos.write(bytes, 0, len);
} // 第九步 判断是否请求成功, 注意:⚠️ success 是自定义服务器返回的 success代表登录成功
String loginResult = bos.toString();
if ("success".equals(loginResult)) { // 不能子在子线程中Toast
// Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show(); threadRunToToast("登录成功"); } else {
// 不能子在子线程中Toast
// Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show(); threadRunToToast("登录失败");
} // 第十步 关闭流
inputStream.close();
bos.close();
}
} /**
* 在 主线程 子线程 中提示,属于UI操作
*/
private void threadRunToToast(final String text) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
}
}
activity_main7.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名"
/> <EditText
android:id="@+id/et_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/> </LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码"
/> <EditText
android:id="@+id/et_pwd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/> </LinearLayout> <Button
android:id="@+id/bt_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text="login"
/> </LinearLayout>

Android-HttpURLConnection-Get与Post请求登录功能的更多相关文章
- Android+struts2+json方式模拟手机登录功能
涉及到的知识点: 1.Struts2框架的搭建(包括Struts2的jSON插件) 2.Android前台访问Web采用HttpClient方式. 3.Android采用JSON的解析. 服务端主要包 ...
- Android-HttpClient-Get与Post请求登录功能
HttpClient 是org.apache.http.* 包中的: 第一种方式使用httpclient-*.jar (需要在网上去下载httpclient-*.jar包) 把httpclient-4 ...
- Android学习笔记_65_登录功能本身没有任何特别
对于登录功能本身没有任何特别,使用httpclient向服务器post用户名密码即可.但是为了保持登录的状态(在各个Activity之间切换时要让网站知道用户一直是处于登录的状态)就需要进行cooki ...
- 为Android游戏接入第三方登录功能
1. “游戏客户端”调用“SDK客户端”的登录功能向“SDK服务端”进行身份认证 2. 验证通过后,“游戏客户端”可得到用户信息,根据游戏逻辑可将用户信息传给“游戏服务器”进行验证 3. “游戏服务器 ...
- android网络编程之HttpUrlConnection的讲解--POST请求
1.服务器后台使用Servlet开发,这里不再介绍. 2.网络开发不要忘记在配置文件中添加访问网络的权限 <uses-permission android:name="android. ...
- android网络编程之HttpUrlConnection的讲解--GET请求
1.服务器后台使用Servlet开发,这里不再介绍. 2.测试机通过局域网链接到服务器上,可以参考我的博客:http://www.cnblogs.com/begin1949/p/4905192.htm ...
- android使用smack实现简单登录功能
android端采用xmpp协议实现即时通讯,在最开始的登录功能就遇到了不少障碍.首先在官网(https://www.igniterealtime.org/projects/openfire/)下载o ...
- Android Studio 通过一个登录功能介绍SQLite数据库的使用
前言: SQLite简介:是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中.它是D.RichardHipp建立的公有领域项目.它的设计目标是嵌入式的,而且目前已经在 ...
- (22)Ajax的基本使用(实现登录功能和局部刷新以及防止跨站请求伪造攻击)
Ajax的作用 前后端分离的项目,需要交互,就要通过Ajax来完成交互 AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即 ...
随机推荐
- POJ 2135.Farm Tour 消负圈法最小费用最大流
Evacuation Plan Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 4914 Accepted: 1284 ...
- POJ1659 Frogs' Neighborhood(青蛙的邻居) Havel-Hakimi定理
Frogs' Neighborhood Time Limit: 5000MS Memory Limit: 10000K Total Submissions: 8729 Accepted: 36 ...
- Hadoop的本地库(Native Libraries)介绍
Hadoop是使用Java语言开发的,但是有一些需求和操作并不适合使用java,所以就引入了本地库(Native Libraries)的概念,通过本地库,Hadoop可以更加高效地执行某一些操作. 目 ...
- 【搜索】C - Catch That Cow
#include<stdio.h> #include<string.h> struct A{ int state; int step; }queue[]; // 结构体数组用来 ...
- Android音频系统之AudioFlinger(三)
http://blog.csdn.net/xuesen_lin/article/details/8805091 1.1.1 PlaybackThread的循环主体 当一个PlaybackThread进 ...
- windows无法卸载jdk的解决方法
装了java之后非常纠结的就是无法卸载,总不能因为卸载一个jdk去重装系统,但是看着它残存在那又非常不爽, 因为卸载会牵扯注册表等琐碎的东西,,,后来在官网发现神器一枚,此神器就是java卸载工具. ...
- centos7 虚拟机安装docker-ce-17.09
1.创建虚拟机使用iso镜像centos-x86_64-7.3.1611 2.安装centos选择桌面版 3.配置命令行环境,网卡(见博客另一篇文章) 4.安装container-selinux-2. ...
- 使用Hadoop API 压缩HDFS文件
下篇解压缩:使用Hadoop API 解压缩 HDFS文件 起因: 集群磁盘剩余空间不足. 删除了存储在HDFS上的,一定时间之前的中间结果,发现并不能释放太多空间,查看计算业务,发现,每天的日志存在 ...
- 733. Flood Fill
class Solution { public: int szx,szy; vector<vector<int>> floodFill(vector<vector< ...
- Explain结果解读与实践
MySQL的EXPLAIN命令用于SQL语句的查询执行计划(QEP).这条命令的输出结果能够让我们了解MySQL 优化器是如何执行SQL 语句的.这条命令并没有提供任何调整建议,但它能够提供重要的信息 ...