我是 JSON 和android联网的新手,我正在尝试编写代码以使用 PHP 从android应用程序更新 mysql 数据库。数小时前,数据库确实使用相同的代码进行了更新,但现在没有。我不明白为什么现在不更新。我正在使用 wamp 服务器。 我知道我需要根据计算机的IP更改url。我相应地对其进行了更改,但数据库未更新。我检查了谷歌,有人建议清除网络浏览器的缓存。我也这样做了,但是什么也没发生。 请帮我。我被卡住了!
这是我的代码:
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new SendRequest().execute();
}
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://172.16.7.90/net.php");
JSONObject postDataParams = new JSONObject();
postDataParams.put("name", "saurav");
postDataParams.put("email", "sau@gmail.com");
Log.e("params", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
return "success";}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first){
first = false};
else{
result.append("&")};
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
这是我的net.php文件:
<?php
$host='localhost';
$username='root';
$password='';
$database='database2';
$name=$_POST['name'];
$email=$_POST['email'];
$dbc=mysqli_connect($host,$username,$password,$database)or die('error');
$sql="INSERT INTO table1(first_name,email)" ."VALUES('$name','$email')";
$result=mysqli_query($dbc,$sql);
mysqli_close($dbc);
?>