php - 使用 HttpURLConnection 使用 php 脚本将数据从 Android POST 到 MYSQL

标签 php android mysql http post

所以,我正在开发一个通过 Android 共享位置的项目,我试图通过将我通过 Android 上的位置 API 获得的纬度、经度数据发布到 MySQL 服务器,使用 PHP 脚本来处理从 Android 发送到 MySQL 的数据。 由于我的目标是 SDK23,因此无法使用标准 Apache 库,而必须使用 Android Studio 提供的 HttpUrlConnection 库。当我发送数据并在 php 上接收它,然后尝试将其存储在 MySQL 数据库中时,只存储空白数据。 这是我的 Android 代码:

package com.example.sid.epics;

import android.location.Location;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.PrintStream;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.net.URLConnection;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;

import java.net.HttpURLConnection;

public class MainActivity extends AppCompatActivity implements
    ConnectionCallbacks,OnConnectionFailedListener {

protected static final String TAG = "basic-location-sample";

protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;

protected String mLatitudeText;
protected String mLongitudeText;

protected java.net.URL url;
protected HttpURLConnection conn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnected(Bundle connectionHint) {
    // Provides a simple way of getting a device's location and is well suited for
    // applications that do not require a fine-grained location and that do not need location
    // updates. Gets the best and most recent location currently available, which may be null
    // in rare cases when a location is not available.
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        mLatitudeText=(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText=(String.valueOf(mLastLocation.getLongitude()));
    } else {
        //Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
        Toast.makeText(this,"No location detected",Toast.LENGTH_LONG).show();
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
    // onConnectionFailed.
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}


@Override
public void onConnectionSuspended(int cause) {
    // The connection to Google Play services was lost for some reason. We call connect() to
    // attempt to re-establish the connection.
    Log.i(TAG, "Connection suspended");
    mGoogleApiClient.connect();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    //int id = item.getItemId();

    //noinspection SimplifiableIfStatement
   /* if (id == R.id.action_settings) {
        return true;
    }*/

    return super.onOptionsItemSelected(item);
}
public void notif(View view) {
    /* post online for now */
    CharSequence text = "Notifcation Toast";
    int duration = Toast.LENGTH_SHORT;
    Toast.makeText(getApplicationContext(),mLatitudeText+" "+mLongitudeText,duration).show();
    new MyAsyncTask().execute();
}

public void navB(View view) {
    /* launch map activity */
}

private class MyAsyncTask extends AsyncTask<String,Void,Double>{
    @Override
    protected Double doInBackground(String... params){
        makePOST();
        return null;
    }
}
public void makePOST(){
    int duration=Toast.LENGTH_SHORT;
    try {
        url = new URL("http://collabu-sidshah.rhcloud.com/notif.php");
        conn=(HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        String postdat="latitude"+ URLEncoder.encode(mLatitudeText,"UTF-8")+"longitude"+URLEncoder.encode(mLongitudeText,"UTF-8");
        //String postdat=mLatitudeText;
        conn.setFixedLengthStreamingMode(postdat.getBytes().length);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        java.io.BufferedOutputStream out = new java.io.BufferedOutputStream(conn.getOutputStream());
        PrintStream pstream=new PrintStream(out);
        pstream.print(postdat);
        pstream.close();
    }
    catch(java.net.MalformedURLException ex){
        //Toast.makeText(this, ex.toString(), duration ).show();
    }
    catch(java.io.IOException ex){
        //Toast.makeText(this, ex.toString(), duration).show();
    }
}
}

这是我在 OpenShift 上运行的 php 脚本

<?php
$location=array();
$parts = explode('&', $HTTP_RAW_POST_DATA);
foreach ( $parts as $part ) {
     list($key, $value) = explode('=', $part, 2);
     for($x=0;$x<2;$x++){
       $location[x]+=$_POST[$key] = $value;
    }
}
$entityBody="\"".$location[0]." ".$$location[1]."\"";
$conn = new mysqli('hostname', 'user',     'password', 'base');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql="INSERT INTO raw_data (raw) VALUES ($entityBody)";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
sleep(1);

最佳答案

值得注意的一件事是,您需要正确设置数据格式,但缺少所需的 &= 字符。

将它们添加到您的数据字符串中,如下所示,它应该可以工作,为了清晰起见,额外换行:

String postdat = "latitude" 
       + "=" 
       + URLEncoder.encode(mLatitudeText,"UTF-8")
       + "&" 
       + "longitude"
       + "="
       + URLEncoder.encode(mLongitudeText,"UTF-8");

有关更详细的信息,请查看此答案: How to add parameters to HttpURLConnection using POST

还有我关于这个主题的博客文章: http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html

关于php - 使用 HttpURLConnection 使用 php 脚本将数据从 Android POST 到 MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792208/

相关文章:

php - 隐藏测验应用程序中最后一个测验的下一个按钮

java - 如何根据自定义标准保持排序的数据结构

mysql - 按月和年创建sql表

mysql - 创建父子表,child 是否需要自己的主 id 列?

javascript - 从 WordPress function.php 调用函数到 page-home.php

处理较小批处理的 PHP Process

android - 发现多个文件的操作系统独立路径为 'protobuf.meta'

mysql - 本赛季出场球员的职业生涯平均水平

php - 如何从一个函数返回多个值

android - 在 Play 商店中以不同的名称发布相同的应用