gpt4 book ai didi

java - 使用 json 将数据从 android 发送到 php

转载 作者:行者123 更新时间:2023-11-30 01:09:10 24 4
gpt4 key购买 nike

嘿,我正在尝试将数据从我的 Android 应用程序发送到 Web 服务器,并使用 mysql 将其发送到数据库,尽管它似乎没有任何错误,但我的代码不起作用

安卓java代码:

                      String categorys=category.getText().toString();
String authors = author.getText().toString();
String quess = question.getText().toString();
String anss = answer.getText().toString();

try {
JSONObject json = new JSONObject();
json.put("category",categorys);
json.put("ques",quess);
json.put("ans",anss);
json.put("authors",authors);
postData(json);


} catch (JSONException e) {
e.printStackTrace();
}

}
});
}

public void postData(JSONObject json) throws JSONException {
HttpClient httpclient = new DefaultHttpClient();

try {
HttpPost httppost = new HttpPost("http://shlomo.webuda.com/androidtomy.php");

List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
nvp.add(new BasicNameValuePair("json", json.toString()));
//httppost.setHeader("Content-type", "application/json");
httppost.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse response = httpclient.execute(httppost);

if(response != null) {
InputStream is = response.getEntity().getContent();
//input stream is response that can be shown back on android
}

}
catch (Exception e)
{
e.printStackTrace();
}




}`

php代码

mysql_connect("something","something","something");
mysql_select_db("something");
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
var_dump($json);
echo "\n\n";

$data = json_decode($json,true);
var_dump($data);




$category=$data['category'];
$author=$data['authors'];
$question=$data['ques'];
$answer=$data['ans'];
$sql = 'INSERT INTO Ques(Ques_Author, Ques_Question,Ques_Answer,Ques_Category,Ques_Approve) values("category","author","question","answer","0")';
mysql_query($sql);

}

?>

最佳答案

正如评论中所指出的,PHP 文件有几个问题。请尝试以下方法:

mysql_connect("something","something","something");
mysql_select_db("something");


$json = $_REQUEST['json'];
echo "JSON: \n";
var_dump($json);
echo "\n\n";

$data = json_decode($json,true);
var_dump($data);

$category=$data['category'];
$author=$data['authors'];
$question=$data['ques'];
$answer=$data['ans'];
$sql = "INSERT INTO Ques(Ques_Author, Ques_Question,Ques_Answer,Ques_Category,Ques_Approve) values($category,$author,$question,$answer,0)";
mysql_query($sql);

您也不应该使用 mysql_query 函数。您应该使用 mysqli_** 函数或 PDO ( http://php.net/manual/en/book.pdo.php )。从 PHP5.5 开始,mysql_query 已被弃用,这是有充分理由的。特别是当您将似乎正确的 url 发布到上述 php 文件时。

如果您仍然遇到问题,请提供 $json 变量的内容以及 Java 代码中的请求副本

关于java - 使用 json 将数据从 android 发送到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19573941/

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