В настоящее время я тестирую код, чтобы привыкнуть к программированию на Android. Я нашел несколько testproject здесь: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/Android: GET работает, POST does not
Но проблема в том, что я могу читать базу данных без проблем, но функции не работают с POST только GET. Поэтому, когда я пытаюсь добавить новый продукт, он выполняет запрос на мой php-скрипт, но никаких POST-данных вообще нет. Я проверил его таким образом:
<?php
header("content-type:application/json; charset=UTF-8");
//print("fda");
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
//if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
//if (isset($_POST['name'])){
$name = "test";//$_POST['name'];
$price = 123; //$_POST['price'];
$description = "desc"; //$_POST['description'];
foreach ($_POST as $key => $value)
$data = $data." Field ".htmlspecialchars($key)." is ".htmlspecialchars($value);
// include db connect class
//echo $data;
$url = $_SERVER['REQUEST_URI'];
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description, url) VALUES('$name', '$price', '$description','$data')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created!.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
//} else {
// // required field is missing
// $response["success"] = 0;
// $response["message"] = "Required field(s) is missing";
//
// // echoing JSON response
// echo json_encode($response);
//}
?>
Как вы видите, я публикую данные POST в базе данных. Когда я использую свой собственный webbased testcript, он отлично работает и показывает данные POST в базе данных.
Так что мой код андроида, кажется, не отправляет данные POST на самом деле, потому что он добавит строку в базу данных, когда я добавлю продукт, но с отключением testvars. Проблема в том, что, когда я его выполню с моего телефона, последнее поле в базе данных (url или более качественные параметры) останется пустым.
Вот код из приложения Android:
package com.example.androidhive;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://www.supergeilebus.nl/android_connect/create_product.php/";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Я надеюсь, что кто-то может мне помочь. У меня нет вариантов. Когда я меняю все на GET, он отлично работает. Я знаю, что он очень плохо кодируется из-за инъекций sql, но я просто хочу узнать об этом.
здоровается и простите за мой плохой английский
Привет, thx для звонка мне Пользователь, я видел, что у меня не было имени. Но вернемся к теме, я попробовал, но у меня нет успеха на самом деле. Он также не отправляет сообщение POST. Может быть, нужно где-то импортировать какой-то дополнительный файл? Может быть, это отправить неправильное предложение? – LiquiDAciD
Привет, Liquacid, Извините, что позвонил пользователю bcoz. Я работал над классом, названным пользователем. В нем я пишу json sting. Нет, вам не нужен внешний файл или банку, чтобы выполнить этот вызов. –