来自Android:
org.apache.http类和 android.net.http.AndroidHttpClient 类已在Android 5.1中弃用。这些类不再被维护,您应该尽快使用这些API将任何应用程序代码迁移到 URLConnection 类。
现在,在Android 5.1中,http类已弃用,如何使用URLConnection将数据插入MySQL数据库?
我目前尝试使用https://stackoverflow.com/a/29561084/2229701中的Fahims代码,但我无法使其正常工作。
insert.php
<?php
// configuration
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$firstname = $_POST['firstname'];
// query
$sql = "INSERT INTO students (firstname) VALUES (:firstname)";
$q = $conn->prepare($sql);
$q->execute(array(':firstname'=>$firstname));
?>
insert.php位于:http:// 192.168.0.5/app/insert.php
这是我目前在MainActivity中的代码:
public void postBtnClicked(View view){
HashMap m = new HashMap();
m.put("firstname", "sam");
performPostCall("http://192.168.0.5/app/insert.php", m);
}
public String performPostCall(String requestURL, HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
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();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}