最好的方法是使用 Volley 库。 Volley 是一个 HTTP 库,它使 Android 应用程序的联网变得更容易,最重要的是更快。
数据由 PHP 生成并使用 Json 数组传递。
您需要同时使用 Android 和 PHP 编程,并提供一个数据库表(示例中未提供 db 表)。还没有提供一个包含名为 Constants.php 的数据库密码的 php 文件。
将 HTTP POST 变量发送到 PHP 服务器并返回一个带有 MySQL 数据的 JSON 数组作为响应。
特点
当您按下 ADD TO MYSQL BUTTON 时发送和接收数据。
它将 POST 变量“名称”和“角色”发送到预定义的 HTTP URL(val url: String)
响应作为 JSONObject 数组返回到 val obj 中。
该示例包含一个 JSONObject,其中一个条目具有 2 个变量“错误”和“消息”
对于 MySQL 和 PHP 中的更多行,您需要遍历 JSON 数组。
VolleySingleton 还有有趣的 ImageLoader 用于图像。您可以跳过此功能
当您想添加从服务器调用的线路时,例如:http://198.128.34.23/main.php?op=dbadd
如果你想得到一些东西,你可以打电话给http://198.128.34.23/main.php?op=dbget
代码轨迹
-没有-
提示
将行<uses-permission android:name="android.permission.INTERNET"/> 放入AndroidManifest
MainActivity 类
package com.stsu.phpjson
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.android.volley.*
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addMyBtn.setOnClickListener { addMySQL() }
}
private fun addMySQL() {
val url:String = "http://198.128.34.23/main.php?op=dbadd"
// val rq:RequestQueue=Volley.newRequestQueue(this)
val stringRequest = object: StringRequest(Request.Method.POST, url,
Response.Listener<String> { response ->
// Process the json
try {
val obj = JSONObject(response)
db_display.text = obj.getString("message")
}catch (e:Exception){
db_display.text = "Exception: $e"
}
}, Response.ErrorListener { error ->
db_display.text = error.message
}) {
@Throws(AuthFailureError::class)
override fun getParams(): Map<String, String>
{
val params = HashMap<String, String>()
params.put("name", "Maria24")
params.put("role", "Parthena243")
return params
}
}
// Add the volley post request to the request queue
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest)
}
}
VolleySingleton 类
package com.stsu.phpjson
import android.app.Application
import android.content.Context
import android.graphics.Bitmap
import android.support.v4.util.LruCache
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.Volley
class VolleySingleton constructor(context: Context)
{
companion object {
@Volatile
private var INSTANCE: VolleySingleton? = null
fun getInstance(context: Context) =
INSTANCE ?: synchronized(this) {
INSTANCE ?: VolleySingleton(context).also {
INSTANCE = it
}
}
}
val imageLoader: ImageLoader by lazy {
ImageLoader(requestQueue,
object : ImageLoader.ImageCache {
private val cache = LruCache<String, Bitmap>(20)
override fun getBitmap(url: String): Bitmap {
return cache.get(url)
}
override fun putBitmap(url: String, bitmap: Bitmap) {
cache.put(url, bitmap)
}
})
}
val requestQueue: RequestQueue by lazy {
// applicationContext is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
Volley.newRequestQueue(context.applicationContext)
}
fun <T> addToRequestQueue(req: Request<T>) {
requestQueue.add(req)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/db_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.425"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.76" />
<Button
android:id="@+id/addMyBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="Add to MySQL"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="266dp" />
</android.support.constraint.ConstraintLayout>
PHP-MAIN-FILE.php
<?php
require_once 'DbOperation.php';
$response = array();
//// http://----Ur IP Address ---/heroapi/HeroApi/v1/?op=addheroes
if(isset($_GET['op'])){
switch($_GET['op']){
/// Check URL and testing API
/// Require POST
case 'dbadd':
if(isset($_POST['name']) && isset($_POST['role'])){
$db = new DbOperation();
if($db->createDemo($_POST['name'], $_POST['role'])){
$response['error'] = false;
$response['message'] = 'Artist added successfully';
}else{
$response['error'] = true;
$response['message'] = 'Could not add artist';
}
}else{
$response['error'] = true;
$response['message'] = 'Required Parameters are missing';
}
break;
////http:
//----FROM your IP Address
////Require GET
case 'dbget':
$db = new DbOperation();
$hero = $db->getDemo();
if(count($hero)<=0){
$response['error'] = true;
$response['message'] = 'Nothing found in the database';
}else{
$response['error'] = false;
$response['hero'] = $hero;
}
break;
case 'file':
if (isset($_FILES["uploaded_file"]["name"]))
{
$name = $_FILES["uploaded_file"]["name"];
$tmp_name = $_FILES["uploaded_file"]["error"];
$error = $_FILES["uploaded_file"]["error"];
if(!empty($name))
{
$location = './assets/';
if(!is_dir($location))
mkdir($location);
if (move_uploaded_file($tmp_name, $location. $name))
{
$response['error'] = false;
$response['message'] = 'Uploaded';
}
else {
$response['error'] = true;
$response['message'] = 'Upload failed';
}
}
else {
$response['error'] = true;
$response['message'] = 'Blank file';
}
}
else {
$response['error'] = true;
$response['message'] = 'NULL POST FILE';
}
break;
case 'filestr':
if (isset($_POST['imstr']) && isset($_POST['filename'])) {
$imstr = $_POST['imstr'];
$filename = $_POST['filename'];
$path = "./";
if (file_put_contents($path. $filename, base64_decode($imstr)) == TRUE) {
$response['error'] = false;
$response['message'] = 'Succesfully uploaded image';
}
else
{
$response['error'] = true;
$response['message'] = 'Server could not save: ';
}
} else {
$response['error'] = true;
$response['message'] = 'Null data received';
}
break;
default:
$response['error'] = true;
$response['message'] = 'No operation to perform';
}
}else{
$response['error'] = false;
$response['message'] = 'Invalid Request';
}
echo json_encode($response);
?>
PHP 包含的文件(将其命名为 DbOperation.php)
<?php
class DbConnect
{
//Variable to store database link
private $con;
//Class constructor
function __construct()
{
}
//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Constants.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return null;
}
//finally returning the connection link
return $this->con;
}
}
?>