dongzhan7253 2015-09-25 23:56
浏览 69

使用HttpURLConnection使用php脚本将数据从Android发布到MYSQL

So, I'm working on a project to share location through Android, which I'm trying to accomplish through posting latitude,longitude data I get through the Location API on Android, to a MySQL server using a PHP script to handle the data sent from Android to the MySQL. Since I'm targeting the SDK23, I am not able to use the standard Apache Library and have to use the HttpUrlConnection library provided by Android Studio. When I send the data and receive it on the php and then try to store it in MySQL database, only blank data gets stored. Here's my Android Code:

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();
    }
}
}

And here's my php script that I'm running on OpenShift

<?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);
  • 写回答

1条回答 默认 最新

  • douping5015 2015-09-26 01:30
    关注

    The one thing that stands out is that you need to format the data properly, you're missing the required & and = characters.

    Add them to your data string like this and it should work, extra line breaks for clarity:

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

    For more detailed info, take a look at this answer: How to add parameters to HttpURLConnection using POST

    And also my blog post on this subject: http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html

    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发