gpt4 book ai didi

java - Android PHP 向 MySQL 发出请求

转载 作者:行者123 更新时间:2023-12-01 14:53:50 26 4
gpt4 key购买 nike

我正在尝试使用 android 向我的服务器发送 http 请求。服务器上有 PHP 脚本,用于添加/删除/编辑 MySQL 数据库中的项目。我无法判断我是否正在连接到服务器或执行代码时发生了什么,我收到 Error parsing data org.json.JSONException: Value

我对 PHP 很陌生,一直在遵循本教程的指导方针“http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/”,但我很困难。

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['name']) && isset($_POST['price']) && isset($_POST['quantity'])) {

$name = $_POST['name'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO drinks(name, price, quantity) VALUES('$name', '$price', '$quantity')");

// 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);
}?>

新饮料 Activity :

public class NewDrinkActivity extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputQuantity;

// url to create new Drink
private static String url_create_Drink = "http://jjohnson.bugs3.com/android_connect/create_drink.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_drink);

// Edit Text
inputName = (EditText) findViewById(R.id.edtName);
inputPrice = (EditText) findViewById(R.id.edtPrice);
inputQuantity = (EditText) findViewById(R.id.edtQuantity);

// Create button
Button btnAddDrink = (Button) findViewById(R.id.btnAdd);

// button click event
btnAddDrink.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
// creating new Drink in background thread
new CreateNewDrink().execute();
}
});
}

/**
* Background Async Task to Create new Drink
* */
class CreateNewDrink extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewDrinkActivity.this);
pDialog.setMessage("Creating Drink..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

/**
* Creating Drink
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String quantity = inputQuantity.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("quantity", quantity));

// getting JSON Object
// Note that create Drink url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_Drink,
"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 Drink
Intent i = new Intent(getApplicationContext(), StockActivity.class);
startActivity(i);

// closing this screen
finish();
} else {
// failed to create Drink
}
} 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();
}

}
}

JSON 解析器:

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

}
}

如果有帮助,我将使用 ServerFree.com 来托管我的文件。

最佳答案

这就是我认为正在发生的事情......

您发出请求,它被发送到服务器并进行处理(正如我所见,PHP 不会出错),然后您会收到如下所示的响应:

{"success":0,"message":"Required field(s) is missing"}

实际上,您从网络服务器收到以下内容:

{"success":0,"message":"Required field(s) is missing"}<!-- www.serversfree.com Analytics Code -->
<script src="http://www.serversfree.com"></script><noscript><a title="Free hosting servers" href="http://www.serversfree.com">Free servers</a><a title="Free websites hosting server" href="http://www.serversfree.com">Free websites hosting server</a><a title="Free hosting server features" href="http://www.serversfree.com/server-features/">Free server features</a><a title="Free hosting" href="http://www.bugs3.com">Free hosting</a></noscript>
<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24425628-3']);
_gaq.push(['_setDomainName', window.location.host]);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

</script>
<!-- End Of Analytics Code -->

因此,尽管您从网站以可视文本形式获取有效的 JSON,但您使用的网络主机正在添加自己的 JavaScript 以便推送其免费服务。

因此,你的 android 中的这些行失败了:

// getting JSON Object
// Note that create Drink url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_Drink,"POST", params);

所以在我看来你有三个选择。

1) 寻找一个不会对您的回复执行此操作的新虚拟主机。您可以尝试在本地计算机上设置 WAMP,这不是很困难。在您了解有关开发的更多信息之前,它对于您的测试来说会更加安全。例如,我们可以通过 SQL 注入(inject)攻击您的数据库。

2) 与该网站合作,看看是否有办法不发送该代码

3) 在 android 调用之前编写一些代码来过滤响应的该部分。您需要创建一个 BufferedReader 等才能接收来自网页的响应。

关于java - Android PHP 向 MySQL 发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14509585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com