当我在网络浏览器中测试我的PHP文件时,我收到消息......
{"成功":0,"消息":"缺少必填字段"}。
我正在尝试将我的Android应用程序中的数据添加到本地主机上的数据库中,并且不知道缺少的必需字段是什么。
我的php脚本是:
<?php
/*
* 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['date']) && isset($_POST['time']) ) {
$date = $_POST['date'];
$time = $_POST['time'];
// include db connect class
require_once __DIR__ . '/connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO datatime(date,time) VALUES('$date', '$time')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "sit created.";
$response["id"] = mysql_insert_id("SELECT id FROM sits ORDER BY id DESC LIMIT 1");
// 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);
}
?>
我的JSON解析器类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
我正在调用我的php文件
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends Activity implements
OnClickListener {
// Widget GUI
//Button btnCalendar, btnTimePicker;
EditText txtDate, txtTime;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
// Variable for storing current date and time
private int mYear, mMonth, mDay, mHour, mMinute;
private static String url_create_product = "http://xxx.yyy.z.xxx/datetimejson/datetime.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtDate = (EditText) findViewById(R.id.txtDate);
txtTime = (EditText) findViewById(R.id.txtTime);
txtDate.setFocusable(false);
txtDate.setClickable(true);
txtTime.setFocusable(false);
txtTime.setClickable(true);
txtDate.setOnClickListener(this);
txtTime.setOnClickListener(this);
Button btnCreateProduct = (Button) findViewById(R.id.set);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(pDialog.isShowing())
pDialog.dismiss();
}
@Override
public void onClick(View v) {
if (v == txtDate) {
// Process to get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Dialog
DatePickerDialog dpd = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// Display Selected date in textbox
txtDate.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
dpd.show();
}
if (v == txtTime) {
// Process to get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
txtTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
tpd.show();
}
}
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String date = txtDate.getText().toString();
String time = txtTime.getText().toString();
// Building Parameters
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
Log.d("Post Update", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Log.d("Updated!", json.toString());
Intent i = new Intent(getApplicationContext(), DailogBox.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();
}
}
}
我已经坚持这个问题几天了,请帮助我。
答案 0 :(得分:0)
有一件事可能是您发出了GET请求,但在PHP脚本中,您使用的是$ _POST数组,只有当它是POST请求时才会有有效数据。
如果您想同时使用GET和POST方法,请在PHP脚本中使用$ _REQUEST。因此将适用于get和POST请求。