Android-HttpClient-Get与Post请求登录功能
HttpClient 是org.apache.http.* 包中的;
第一种方式使用httpclient-*.jar (需要在网上去下载httpclient-*.jar包)

把httpclient-4.5.jar/httpclient-4.4.1.jar包放入到libs里,然后点击sync project ...才能使用httpclient-4.5.jar包

httpclient-4.5.jar不好用,建议使用httpclient-4.4.1.jar

第二种方式:配置AndroidStudio 的方式获取 HttpClient
在相应的module下的build.gradle中加入:useLibrary 'org.apache.http.legacy'
这条语句一定要加在 android{ } 当中,然后rebulid
例如:

app/build.gradle android { useLibrary 'org.apache.http.legacy' }

apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "liudeli.async"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
useLibrary 'org.apache.http.legacy'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

在AndroidManifest.xml加入权限:
<!-- 访问网络是危险的行为 所以需要权限 -->
<uses-permission android:name="android.permission.INTERNET" /> <!-- 设置壁纸是危险的行为 所以需要权限 -->
<uses-permission android:name="android.permission.SET_WALLPAPER" />
MainActivity6:
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 org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class MainActivity6 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_main6); 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();
} /**
* HttpClient 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 // 第一步 创建HttpClient
HttpClient httpClient = new DefaultHttpClient(); // 第三步 创建请求对象 Get
HttpUriRequest getRequest = new HttpGet(pathString.toString()); // 第二步 执行请求,获取响应对象
HttpResponse response = httpClient.execute(getRequest); // 第四步 判断请求是否成功
if (response.getStatusLine().getStatusCode() == 200) { // 第五步 获取响应的流
InputStream inputStream = response.getEntity().getContent(); 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("登录失败,请检查网络!");
}
} /**
* HttpClient Get 方式请求
* @param path 请求的路径
* @param map 请求的参数
* 路径:http://127.0.0.1:8080/LoginServlet
*
* 参数:
* name=zhangsan
* pwd=123456
*/
private void loginByPost(String path, Map<String, String> map) throws Exception { // 第一步 创建HttpClient
HttpClient httpClient = new DefaultHttpClient(); // 第三步 创建请求对象 Post
HttpPost postRequest = new HttpPost(path); // 第六步 参数封装操作
List<NameValuePair> nameValuePairs = new ArrayList<>();
for (Map.Entry<String, String> mapItem : map.entrySet()) {
// 遍历Map集合里面的 key value >>> name=zhangsan pwd=123456
String key = mapItem.getKey();
String value = mapItem.getValue(); // 创建参数对象
NameValuePair nameValuePair = new BasicNameValuePair(key, value); // 把参数对象放入List<NameValuePair>集合
nameValuePairs.add(nameValuePair);
} // 第五步 创建实体对象 传入参数>>>List<? extends NameValuePair>
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8"); // 第四步 把请求的参数 放入实体
postRequest.setEntity(entity); // 第二步 执行请求,获取响应对象
HttpResponse response = httpClient.execute(postRequest); // 第七步 判断请求是否成功
if (response.getStatusLine().getStatusCode() == 200) { // 第八步 获取响应的流
InputStream inputStream = response.getEntity().getContent(); 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("登录失败,请检查网络!");
}
} /**
* 在 主线程 子线程 中提示,属于UI操作
*/
private void threadRunToToast(final String text) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
}
}
activity_main6.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-HttpClient-Get与Post请求登录功能的更多相关文章
- Android HttpClient GET或者POST请求基本使用方法(转)
在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.这里只介绍如何使用HttpCl ...
- Android+struts2+json方式模拟手机登录功能
涉及到的知识点: 1.Struts2框架的搭建(包括Struts2的jSON插件) 2.Android前台访问Web采用HttpClient方式. 3.Android采用JSON的解析. 服务端主要包 ...
- Android-HttpURLConnection-Get与Post请求登录功能
HttpURLConnection 在这请求方式是Java包中的: AndroidManifest.xml配置权限: <!-- 访问网络是危险的行为 所以需要权限 --> <uses ...
- Android学习笔记_65_登录功能本身没有任何特别
对于登录功能本身没有任何特别,使用httpclient向服务器post用户名密码即可.但是为了保持登录的状态(在各个Activity之间切换时要让网站知道用户一直是处于登录的状态)就需要进行cooki ...
- 为Android游戏接入第三方登录功能
1. “游戏客户端”调用“SDK客户端”的登录功能向“SDK服务端”进行身份认证 2. 验证通过后,“游戏客户端”可得到用户信息,根据游戏逻辑可将用户信息传给“游戏服务器”进行验证 3. “游戏服务器 ...
- 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”.即 ...
- 实现Web请求后端Api的Demo,实现是通过JQuery的AJAX实现后端请求,以及对请求到的数据的解析处理,实现登录功能
本篇实现Web请求后端Api的Demo,实现是通过JQuery的AJAX实现后端请求,以及对请求到的数据的解析处理,实现登录功能需求描述:1. 请求后端Api接口地址2. 根据返回信息进行判断处理前端 ...
随机推荐
- 201621123008 《Java程序设计》 第11周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多线程相关内容. 2. 书面作业 本次PTA作业题集多线程 1. 源代码阅读:多线程程序BounceThread 1.1 BallR ...
- Django报错:__init__() missing 1 required positional argument: 'on_delete'
原因: 在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错:TypeError: __init__() missing ...
- linux 常用命令(三)ssh
linux 常用命令(三)SSH 一.SSH 安装及免密登陆 (1) SSH 安装并配置 CentOS 默认已安装了 SSH client.SSH server,打开终端执行如下命令进行检验 rpm ...
- android Run模式也会出现"Waiting for debugger"的解决方法
android Run模式也会出现"Waiting for debugger"的解决方法 出现“waiting for debugger”窗口是在debug模式下运行出现的.但是, ...
- 【转载】 H264的I/P/B帧类型判断
http://blog.csdn.net/zhuweigangzwg/article/details/44152239 这里首先说明下H264的结构: 00 00 00 01/00 00 01-> ...
- Windows 8风格应用-触控输入
参考:演练:创建您的第一个触控应用程序 http://msdn.microsoft.com/zh-cn/library/ee649090(v=vs.110).aspx win8支持多点触摸技术,而我们 ...
- [VBS]检测计算机各硬件信息
1)批处理脚本:Rhea_HardwareInfoCollector.bat 调用VBScript脚本Rhea_HardwareInfoCollector.vbs,并将结果打印到文件Rhea_Resu ...
- nginx 502 Bad Gateway 错误解决办法
nginx出现502有很多原因,但大部分原因可以归结为资源数量不够用,也就是说后端PHP-fpm处理有问题,nginx将正确的客户端请求发给了后端的php-fpm进程,但是因为php-fpm进程的问题 ...
- s5-11 距离矢量路由选择协议
距离矢量路由选择(Distance Vector:DV) 每个路由器维护一张表,表中列出了当前已知的到每个目标 的最佳距离,以及为了到达那个目标,应该从哪个接口转发. 距离矢量路由选择(Distanc ...
- 第17章:MongoDB-聚合操作--聚合管道--$group
①$group 作用:将集合中的文档进行分组,可用于统计结果. 例如: db.scores.aggregate({“$group”:{“_id”:“$studentId”}}); 或者是 db.sco ...