實作功能:Android app發ID資料給IDEA
后臺,后臺根據獲取到的ID資料查詢資料庫并將對應的資料發回客戶端顯示在app界面
開發工具:IDEA,Android studio,MySQL
Android端:(以下為需要新建或者修改的檔案,以便新手學習)
Java:MainActivity
GuestToServer
layout:activity_main
build.gradle(app)
AndoidManifest.xml
客戶端運行示例:

代碼展示:
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.myapplication.MainActivity.this, "登錄成功!", Toast.LENGTH_LONG).show();
}
//登錄失敗
else{ Toast.makeText(com.example.myapplication.MainActivity.this, "登錄失敗!", Toast.LENGTH_LONG).show();
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
GuestToServer guestToServer = new GuestToServer();
try {
//如果是呼叫GuestToServer中驗證用戶名與密碼的方法則使用下面句
//String result = guestToServer.doPost(et_username.getText().toString().trim(), et_password.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組件
}
}
GuestToServer
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.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
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 GuestToServer {
//localhost為本地主機IP地址/login為idea后臺專案名
private String url = "http://localhost:8080/login";
//服務器回傳的結果//
String result = "";
/**
* 使用Post方式向服務器發送請求并回傳回應
*
* //如果使用驗證用戶名及密碼的方法那么使用public String doPost(String username, String password) throws IOException {
* //且放出下面兩句引數設定
// * @param username 傳遞給服務器的username
// * @param password 傳遞給服務器的password
* @param id 傳遞給服務器的id
* @return
*/
public String doPost(String id) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
NameValuePair param3 = new BasicNameValuePair("id", id);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(param3);
//將引數包裝如HttpEntity中并放入HttpPost的請求體中
HttpEntity httpEntity = new UrlEncodedFormEntity(params, "GBK");
httpPost.setEntity(httpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
//如果回應成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//得到資訊體
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String readLine = null;
while ((readLine = br.readLine()) != null) {
result += readLine;
}
inputStream.close();
return result;
}
//回應失敗
else {
return "false";
}
}
/*
public String doPost(String username, String password) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
//將username與password引數裝入List中
NameValuePair param1 = new BasicNameValuePair("username", username);
NameValuePair param2 = new BasicNameValuePair("password", password);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(param1);
params.add(param2);
//將引數包裝如HttpEntity中并放入HttpPost的請求體中
HttpEntity httpEntity = new UrlEncodedFormEntity(params, "GBK");
httpPost.setEntity(httpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
//如果回應成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//得到資訊體
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String readLine = null;
while ((readLine = br.readLine()) != null) {
result += readLine;
}
inputStream.close();
return result;
}
//回應失敗
else {
return "false";
}
}*/
}
activity_main.xml
<?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:id="@+id/activity_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:text="登錄界面"
android:textSize="10dp"
android:textColor="#003399"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:gravity="center_horizontal"
android:layout_margin="10dp"/>
<TextView
android:text="用戶名"
android:textSize="20dp"
android:textColor="#CC0000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:layout_margin="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/et_username"
android:textSize="10dp"
android:textColor="#003399"
android:layout_margin="10dp"/>
<TextView
android:text="密碼 "
android:textSize="20dp"
android:textColor="#CC0000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView3"
android:layout_margin="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/et_password"
android:textSize="10dp"
android:textColor="#003399"
android:layout_margin="10dp"/>
<TextView
android:text="ID "
android:textSize="20dp"
android:textColor="#CC0000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/idtextview"
android:layout_margin="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/id"
android:textSize="10dp"
android:textColor="#003399"
android:layout_margin="10dp"/>
<Button
android:text="登錄"
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt_login"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#0099FF"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv"/>
</LinearLayout>
如果專案出現報錯,記得檢查報錯日志,一般是apache沒有匯入
在build.gradle里加入這行
useLibrary’org.apache.http.legacy’

由于版本不同,有些需要在manifest檔案中的appication加入
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
至此,Android app搭建完畢,可試運行
IDEA后臺專案搭建:
可參考上一篇小程式后臺,共用一個后臺與資料庫無需更改
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/354613.html
標籤:其他
下一篇:JSP實作大學生綜合素質測評系統
