簡體   English   中英

使用HttpURLConnection使用php腳本將數據從Android POST到MYSQL

[英]Using HttpURLConnection to POST data from Android to MYSQL using a php script

因此,我正在一個項目中通過Android共享位置,我試圖通過將通過Android上的Location API獲得的緯度,經度數據發布到使用PHP腳本處理發送數據的MySQL服務器上來完成此任務從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");

有關更多詳細信息,請看以下答案: 如何使用POST向HttpURLConnection添加參數

還有關於這個主題的我的博客文章: http : //danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM