Android程序通过Apache服务器执行PHP程序连接Mysql数据库(重要!)

原创 2015年11月18日 14:27:48

看了网上别人的文章弄了许久,总算成功了,提醒一下,android程序得导入包org.apache的jar包.


db_config.php:

<?php
/**
 * Created by PhpStorm.
 * User: Ollydebug
 * Date: 2015/11/17
 * Time: 20:05
 */

define('DB_USER',"root");   //db user
define('DB_PASSWORD',"");   //db password
define('DB_DATABASE',"test");   //database name
define('DB_SERVER',"localhost");  //db server


?>


server.php:

<?php
/**
 * Created by PhpStorm.
 * User: Ollydebug
 * Date: 2015/11/17
 * Time: 19:48
 */

include('db_config.php');

$address = $_POST['address'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$id = $_POST['_id'];
$tableName = "androidtable";

if(empty($address)or empty($longitude)or empty($latitude)){
    die("You have to fill all the fields!");
}
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD);

if(!$conn){
    die("connection failed:".mysql_error());
}

mysql_select_db(DB_DATABASE,$conn);

$query = "insert into ".$tableName." values(".$id.",'".$address."',".$longitude.",".$latitude.",'".date('Y-m-d H:i:s',time())."');";

$result = mysql_query($query,$conn);

if(!$result){
    die("mysql error:".mysql_error());
}


echo "add information to database sucessfullly!";



?>


Android:

请求网络为耗时操作,必须操作在子线程当中.另外别忘了加权限.题主开头各种坑......

   <uses-permission android:name="android.permission.INTERNET" />


java:

(啰嗦一下,PHP文件得放到apache服务器的文件夹下,然后注意不能用localhost)

android访问服务器的时候不能用localhost或者127.0.0.1,因为android自己本身也有本地服务器,这样就找不到你的地址,

必须得用内网的ip地址,切记!!


package com.example.ollydebug.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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.ClientProtocolException;
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 org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private TextView tv = null;
    private Button button = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.outputTxt);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("-->开启子线程");
                new TaskThread().start();
            }
        });
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                {
                    System.out.println("-->回到主线程刷新ui任务");
                    String result = "add information to database sucessfullly!";
                    tv.setText(result);
                    Log.i(TAG,"result = "+result);
                }
                break;

                default:
                    break;
            }
        };
    };


    class TaskThread extends Thread {
        public void run() {
            System.out.println("-->做一些耗时的任务");
            String url = "http://172.19.82.99/AndroidInteraction/server.php";
            HttpPost httpRequest = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("_id","1"));
            params.add(new BasicNameValuePair("address", "yinchengzhi"));
            params.add(new BasicNameValuePair("longitude", "100.252255"));
            params.add(new BasicNameValuePair("latitude", "-15.415121"));
            try {
                HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
                httpRequest.setEntity(httpEntity);
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse httpResponse = httpClient.execute(httpRequest);
                if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    String result = EntityUtils.toString(httpResponse.getEntity());
                    System.out.println(result);

                    /*
                    如果要更新视图不能在子线程中更新,只能在主线程中刷新UI
                    tv.setText(result);
                    Log.i(TAG,"result = "+result);
                    */

                    Message msg = new Message();
                    msg.what = 0;
                    handler.sendMessage(msg);

                }else{
                    tv.setText("request error");
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.sendEmptyMessage(0);
        };
    };

}


xml:

(这个简单!不罗嗦了!)

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.ollydebug.myapplication.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>




版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Android 登录界面连接PHP后台服务器

package com.login.main;import java.io.IOException;import java.io.UnsupportedEncodingException;import...

Android+PHP+MYSQL开发简单实例

Android+PHP+MYSQL开发简单实例 前段时间做了一个安卓项目,需要用到数据库,之前有写过一点网页相关的东西,所以打算用MYSQL+PHP这个黄金搭档,虽然有点大材小用了。 本人是个货真价实...

Android与PHP服务器数据连接源码

Android客户端的源码: /*** * * @author 马琳的笔记本 * @date 2015 9-17 * 测试第一个对应user1.php */ public class Ma...

Learning Perl: 8.8. Precedence

8.8. PrecedenceWith all of these metacharacters in regular expressions, you may feel you can't keep ...

将Apache的访问日志实时写入mysql数据库

在apache配置文件或是虚拟主机配置文件中(也就是配置LogFormat以及CustomLog部分)增加如下内容: LogFormat "INSERT INTO apachelog (ID, ...
  • linlzk
  • linlzk
  • 2015-08-14 16:53
  • 1204

使用IIS服务器托管Apache服务器上的PHP程序

在我们对程序进行线上部署的时候会遇到这样的问题:一个服务器中已经部署了.NET程序,此时的80端口已经被占用,所以当我们要部署PHP程序时由于80端口已被调用,所以进行域名访问时会出现错误。则此时我们...

Mac服务器搭建以及MySQL数据库使用:Apache(Tomcat,Resin),PHP,MYSQL,Navicat

1.Apache服务器  Mac OS X内置Apache服务器,但默认没有启动 查看Apache版本: sudo apachectl -v 启动、关闭、重启Apache: sudo apachect...

apache的httpd.conf文件配置和第一个php程序

-----   apache的安装路径                    ...

使用apache mod_env模块保存php程序敏感信息

Apache模块 mod_env 说明:允许Apache修改或清除传送到CGI脚本和SSI页面的环境变量 模块名:env_module 源文件:mod_env.c 本模块用于控制传送给CGI脚本和S...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)