我试图将一个post参数发送到我的php文件
<?php
$sid = $_POST['sid'];
ini_set( 'error_reporting', E_ALL );
ini_set( 'display_errors', true );
include 'dbconfig.php';
//include 'sql.php';
//include 'pass.php';
ob_start();
include 'pass.php';
ob_end_clean() ;
/* if($_SERVER['REQUEST_METHOD']=='POST'){*/
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn,'utf8');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM lime_questions where sid=$sid";
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem, JSON_UNESCAPED_UNICODE);
}
} else {
echo "0 results";
}
$data= strip_tags ($json);
echo str_replace('success','',$data);
//$encoded=json_decode($json);
//print_r($encoded);
//echo json_last_error_msg();
$conn->close();
?>
$ sid变量必须从我的jsonarrayrequest发送而不是parse收到的问题,这是我的java代码:我使用jsonarrayrequest从我的服务器获取数据到我的应用程序
public void LoadData() {
Bundle extras = getIntent().getExtras();
//sid = extras.getString(Login.KEY_URL);
sid="1994";
JsonArrayRequest newsReq1 = new JsonArrayRequest(url1, new
Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
String sqid = obj.getString("sid");
String gid = obj.getString("gid");
String id = obj.getString("qid");
String q = obj.getString("question");
String t = obj.getString("type");
insertIntoDB(sqid, gid, id, q, t);
test.setText(q);
NewsQuestions question = new NewsQuestions(id,
q, t);
// adding question to questions array
questionsList.add(question);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
}}
)
{
@Override
protected Map<String, String> getParams() throws
AuthFailureError {
Map<String, String> params = new HashMap<String, String>
();
params.put(KEY_URL,sid);
return params;
}
@Override
public int getMethod() {
try {
getParams();
} catch (AuthFailureError authFailureError) {
authFailureError.printStackTrace();
}
return super.getMethod();
}
};
我的问题是如何从我的Android应用程序发送sid参数到我的文件
答案 0 :(得分:0)
使用StringRequest而不是JsonArrayRequest
转到:https://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
答案 1 :(得分:0)
这是使用android movil
发送GPS位置的示例package com.panic.root.panic;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.telephony.gsm.SmsManager;
@SuppressWarnings("deprecation")
@SuppressLint("HandlerLeak")
public class EnvioPanicActivity extends Activity {
//textBox y demas elementos del activity
private Cursor dbCursor;
private String tableName;
private String fieldName;
private String[] from;
private DBAdapter db;
private ProgressDialog pDialog;
private Handler puente = new Handler() {
@Override
public void handleMessage(Message msg) {
//Mostramos el mensage recibido del servidor en pantalla
Toast.makeText(getApplicationContext(), (String) msg.obj,
Toast.LENGTH_LONG).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Acceder a datos de los Contactos para el envío de mensajes--------------------
db = new DBAdapter(getApplicationContext());
db.open();
tableName = DBOpenHelper.TABLE_CUSTOMER;
fieldName = DBOpenHelper.CUSTOMER_COL_PHONE;
from = new String[] { "_id", "phone" };
dbCursor = db.getCursor(tableName,from,null,null);
// Obtenemos los índices de las columnas
int nameColumn = dbCursor.getColumnIndex(fieldName);
//int phoneColumn = dbCursor.getColumnIndex(People.NUMBER);
//Recorremos el cursor
for(dbCursor.moveToFirst(); !dbCursor.isAfterLast(); dbCursor.moveToNext()){
String phone = dbCursor.getString(nameColumn);
enviarSMS(phone);
}
//---------------------------------------------------------------------------
new SendData().execute();
}
@SuppressWarnings("rawtypes")
private class SendData extends AsyncTask {
@Override
protected Object doInBackground(Object... arg0) {
Datasend();
return null;
}
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EnvioPanicActivity.this);
pDialog.setMessage("Enviando Auxilio..por favor espere");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
}
private void Datasend(){
//Utilizamos la clase Httpclient para conectar
HttpClient httpclient = new DefaultHttpClient();
//Utilizamos la HttpPost para enviar lso datos
//A la url donde se encuentre nuestro archivo receptor
HttpPost httppost = new HttpPost("http://192.168.0.25/aguara/datareceptor.php");
try {
List<NameValuePair> postValues = new ArrayList<NameValuePair>(2);
postValues.add(new BasicNameValuePair("latitud", getIntent().getStringExtra("latitud")));
postValues.add(new BasicNameValuePair("longitud", getIntent().getStringExtra("longitud")));
postValues.add(new BasicNameValuePair("precision", getIntent().getStringExtra("precision")));
postValues.add(new BasicNameValuePair("imei", getIntent().getStringExtra("imei")));
//Encapsulamos
httppost.setEntity(new UrlEncodedFormEntity(postValues));
//Lanzamos la petici�n
HttpResponse respuesta = httpclient.execute(httppost);
//Conectamos para recibir datos de respuesta
HttpEntity entity = respuesta.getEntity();
//Creamos el InputStream como su propio nombre indica
InputStream is = entity.getContent();
//Limpiamos el codigo obtenido atraves de la funcion
//StreamToString explicada m�s abajo
String resultado= StreamToString(is);
//Enviamos el resultado LIMPIO al Handler para mostrarlo
Message sms = new Message();
sms.obj = resultado;
//Vuelve al Activity anterior
finish();
}catch (IOException e) {
//TODO Auto-generated catch block
}
}
//Funcion para 'limpiar' el codigo recibido
public String StreamToString(InputStream is) {
//Creamos el Buffer
BufferedReader reader =
new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
//Bucle para leer todas las l�neas
//En este ejemplo al ser solo 1 la respuesta
//Pues no har�a falta
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//retornamos el codigo l�mpio
return sb.toString();
}
private void enviarSMS(String phone){
try {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phone,null,"Mensaje de Alerta recibido. Lat: "+getIntent().getStringExtra("latitud")
+" Long: "+getIntent().getStringExtra("longitud"),null,null);
Toast.makeText(getApplicationContext(), "Mensaje de Alerta enviado.", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Mensaje no enviado, datos incorrectos.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
这是来自服务器的代码
<?php
//Recibimos el parametro des de Android
include './funciones.php';
conexionlocal();
$latitud = $_REQUEST['latitud'];
$longitud = $_REQUEST['longitud'];
$precision = $_REQUEST['precision'];
$IMEI = $_REQUEST['imei'];
$codigo_persona=obtenerCodigoPersona($IMEI);
if ($codigo_persona<> "")
{
$query = "INSERT INTO alertas(al_posx,al_posy,al_precision,al_imei,al_estado,al_confirm,al_procesado,al_fecha,per_cod)"
. "VALUES ($latitud,$longitud,$precision,$IMEI,'t','f','f',now(),$codigo_persona);";
//ejecucion del query
$ejecucion = pg_query($query)or die('Error 108:'.$query);
echo ("SERVER: Datos Recibidos Exitosamente..!");
}else
{
$query = "INSERT INTO alertas_otros(al_posx,al_posy,al_precision,al_imei,al_estado,al_confirm,al_procesado,al_fecha)"
. "VALUES ($latitud,$longitud,$precision,$IMEI,'t','f','f',now());";
//ejecucion del query
$ejecucion = pg_query($query)or die('Error 108:'.$query);
echo ("SERVER: Datos Recibidos Exitosamente..!");
}
?>