首先上Android的文件结构图
MainActivity的代码如下
package com.example.logintest2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
//登录用户名输入框
private EditText et_username;
//登录密码输入框
private EditText et_password;
//登录按钮
private EditText id;
private Button bt_login;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取组件
init();
//对登录按钮的点击监控
bt_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(LoginActivity.this, "登录成功!", Toast.LENGTH_LONG).show();
final Handler myHandler = new Handler(){
public void handleMessage(Message msg){
String responseResult = (String)msg.obj;
// Toast.makeText(LoginActivity.this, "登录成功!", Toast.LENGTH_LONG).show();
//登录成功
System.out.println("response+"+responseResult);
try{
JSONObject root = new JSONObject(responseResult);
String userName = root.getString("userName");
tv.append("userName"+"="+userName+"\n");
}
catch (JSONException e) {
e.printStackTrace();
}
if(responseResult.equals("" +
"true")){ Toast.makeText(com.example.logintest2.MainActivity.this, "登录成功!", Toast.LENGTH_LONG).show();
}
//登录失败
else{ Toast.makeText(com.example.logintest2.MainActivity.this, "登录失败!", Toast.LENGTH_LONG).show();
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
GuestToServer2 guestToServer = new GuestToServer2();
try {
//如果是调用GuestToServer中验证用户名与密码的方法则使用下面句
String result = guestToServer.doPost(et_username.getText().toString().trim(), et_password.getText().toString().trim(),id.getText().toString().trim());
// String result = guestToServer.doPost(id.getText().toString().trim());
Message msg = new Message();
msg.obj = result;
myHandler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
/**
* 获取组件
*/
private void init() {
et_username = (EditText)findViewById(R.id.et_username);
et_password = (EditText)findViewById(R.id.et_password);
id= (EditText)findViewById(R.id.id);
bt_login = (Button)findViewById(R.id.bt_login);
tv = (TextView) findViewById(R.id.tv);//获取到TextView组件
}
}
主要是通过按键调用 GuestToServer2的方法,同理可以加入查询,登录等功能
package com.example.logintest2;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class GuestToServer2 {
//localhost为本地主机IP地址/test为idea后台项目中UserCotroller中的@RequestMapping名字分级到具体方法
private String url = "http://ip:8080/test/register";
//服务器返回的结果//
String result = "";
public String doPost(String username, String password,String id) throws IOException {
//用post方法传送的参数是id
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//拼接参数
NameValuePair param1 = new BasicNameValuePair("userName", username);
NameValuePair param2 = new BasicNameValuePair("passWord", password);
NameValuePair param3 = new BasicNameValuePair("id", id);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(param1);
params.add(param2);
params.add(param3);
System.out.println(params);
//参数放入实体
httpPost.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response2 = httpClient.execute(httpPost);
//返回response2
HttpEntity httpEntity = new UrlEncodedFormEntity(params, "GBK");
httpPost.setEntity(httpEntity);
//正常HttpStatus.SC_OK应该是200,response2.getStatusLine().getStatusCode()状态是200表示连接正常
if (response2.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//得到信息体
HttpEntity entity = response2.getEntity();
InputStream inputStream = entity.getContent();
//将实体里的内容获取出来循环读取放入result,这里我们是根据发出去的id获取回来username,password,realname
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String readLine = null;
while ((readLine = br.readLine()) != null) {
result += readLine;
}
inputStream.close();
return result;
}
//响应失败
else {
return "false0";
}
}
//DefaultHttpClient —> CloseableHttpClient
//HttpResponse —> CloseableHttpResponse
public static CloseableHttpClient createDefault() {
return HttpClientBuilder.create().build();
}
}
build.app文件
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.logintest2'
compileSdk 33
defaultConfig {
applicationId "com.example.logintest2"
minSdk 24
targetSdk 33
versionCode 1
versionName "1.0"
useLibrary'org.apache.http.legacy'
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'org.apache.httpcomponents:httpmime:4.3.6'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
manifest文件加权限
后台项目使用的和上一篇的小程序登陆注册是同一个idea项目,数据库的表格也是共用的没问题