1、首先输入代码
public void SendByHttpClient(final String id, final String pw){
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpclient=new DefaultHttpClient()
HttpPost httpPost=new HttpPost("http://web应用部署服务器上的IP地址:/HttpClientDemo/Login")//服务器地址,指向Servlet
List<NameValuePair>params=new ArrayList<NameValuePair>()//将id和pw装入list
params.add(new BasicNameValuePair("ID",id))
params.add(new BasicNameValuePair("PW",pw))
final UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8")//以UTF-8格式发送
httpPost.setEntity(entity)
HttpResponse httpResponse= httpclient.execute(httpPost)
if(httpResponse.getStatusLine().getStatusCode()==200)//在200毫秒之内接收到返回值
2、然后再输入下方的代码:
{
HttpEntity entity=httpResponse.getEntity()
String response=EntityUtils.toString(entity1, "utf-8")//以UTF-8格式解析
Message message=new Message()
message.what=USER_LOGIN
message.obj=response
handler.sendMessage(message)使用Message传递消息给线程
}
}
catch (Exception e) {
e.printStackTrace()
}
}
}).start()
}3、最终,测试结果图,如下:
使用JSON连接Android和PHP Mysql数据库方法:1、打开安装WAMP Server的文件夹,打开www文件夹,为你的项目创建一个新的文件夹。必须把项目中所有的文件放到这个文件夹中。
2、新建一个名为android_connect的文件夹,并新建一个php文件,命名为test.php,尝试输入一些简单的php代码(如下所示)。
test.php
<?php
echo"Welcome, I am connecting Android to PHP, MySQL"
?>
3、创建MySQL数据库和表
创建了一个简单的只有一张表的数据库。用这个表来执行一些示例 *** 作。现在,请在浏览器中输入http://localhost/phpmyadmin/,并打开phpmyadmin。你可以用PhpMyAdmin工具创建数据库和表。
创建数据库和表:数据库名:androidhive,表:product
CREATE TABLE products(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
)
4、用PHP连接MySQL数据库
现在,真正的服务器端编程开始了。新建一个PHP类来连接MYSQL数据库。这个类的主要功能是打开数据库连接和在不需要时关闭数据库连接。
新建两个文件db_config.php,db_connect.php
db_config.php--------存储数据库连接变量
db_connect.php-------连接数据库的类文件
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root")// db user
define('DB_PASSWORD', "")// db password (mention your db password here)
define('DB_DATABASE', "androidhive")// database name
define('DB_SERVER', "localhost")// db server
?>
5、在PHP项目中新建一个php文件,命名为create_product.php,并输入以下代码。该文件主要实现在products表中插入一个新的产品。
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array()
// check for required fields
if (isset($_POST['name']) &&isset($_POST['price']) &&isset($_POST['description'])) {
$name = $_POST['name']
$price = $_POST['price']
$description = $_POST['description']
// include db connect class
require_once __DIR__ . '/db_connect.php'
// connecting to db
$db = new DB_CONNECT()
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')")
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1
$response["message"] = "Product successfully created."
// echoing JSON response
echo json_encode($response)
} else {
// failed to insert row
$response["success"] = 0
$response["message"] = "Oops! An error occurred."
// echoing JSON response
echo json_encode($response)
}
} else {
// required field is missing
$response["success"] = 0
$response["message"] = "Required field(s) is missing"
// echoing JSON response
echo json_encode($response)
}
?>
JSON的返回值会是:
当POST 参数丢失
[php] view plaincopy
{
"success": 0,
"message": "Required field(s) is missing"
}
一、首先要加载JDBC驱动包。步骤:右击项目找到build path->configure build path->libraries——>add External JARs添加驱动包
二、写测试类:TestCon.java
(在此之前,首先
1.在自己的电脑上Mysql下确定账户是"root",密码是"123456";
2.进入账户,创建数据库cui;
3.在数据库cui下面,创建表test1 包含_id(int 类型自动增加) username(String 类型)、password(String 类型);
4.在表中插入数据,以便显示
)
1 package com.test.an
2
3 import java.sql.Connection
4 import java.sql.DriverManager
5 import java.sql.PreparedStatement
6 import java.sql.ResultSet
7 import java.sql.SQLException
8
9
10 public class TestCon1{
11 public static void main(String[] args)
12 {
13 Connection con = null
14 String sql
15 PreparedStatement pre
16 ResultSet rs
17
18 try {
19 String driver="com.mysql.jdbc.Driver"
20 Class.forName(driver)
21
22 String url="jdbc:mysql://localhost:3306/cuiuseUnicode=true&characterEncoding=latin1"//utf-8也行
23 con = DriverManager.getConnection(url, "root", "123456")
24
25 sql = "select _id,username,password from test1"
26 pre = con.prepareStatement(sql)
27
28 rs = pre.executeQuery()
29 while(rs.next()){
30 int id = rs.getInt(1)
31 String username = rs.getString(2)
32 String password = rs.getString(3)
33
34 System.out.println("id="+id+"username="+username+"password="+password)
35 }
36 con.close()
37 } catch (SQLException e) {
38 e.printStackTrace()
39 } catch (ClassNotFoundException e) {
40 e.printStackTrace()
41 }
42
43 }
44
45 }
运行结果:
id=1username=cccpassword=123456
id=2username=xxxpassword=654321
id=3username=dddpassword=123456
id=4username=ddf÷password=yyt
id=5username=cuixiaodongpassword=cxd
id=6username=vvpassword=cxd
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)