2015-09-25 66 views
0

因此,我正在通過Android共享位置的項目,我試圖通過發佈緯度和經度數據來實現位置API在Android上,使用PHP腳本處理從Android發送到MySQL的數據到MySQL服務器。 由於我的目標是SDK23,因此我無法使用標準的Apache庫,必須使用Android Studio提供的HttpUrlConnection庫。當我發送數據並在PHP上接收數據,然後嘗試將其存儲在MySQL數據庫中時,只會存儲空白數據。 這裏是我的Android代碼:使用HttpURLConnection使用PHP腳本將數據從Android發佈到MYSQL

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

回答

0

的一兩件事,突出的是,你需要的數據格式正確,你」重新缺少所需的&=個字符。

他們添加到你這樣的數據串,它應該工作,額外的線清晰突破:

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

相關問題