From Android:
The org.apache.http classes and the android.net.http.AndroidHttpClient class have been deprecated in Android 5.1. These classes are no longer being maintained and you should migrate any app code using these APIs to the URLConnection classes as soon as possible.
Now that the http classes are Deprecated in Android 5.1, how would I insert data into a MySQL database using URLConnection?
I currently have tried using Fahims code from https://stackoverflow.com/a/29561084/2229701, but I cannot get it working.
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 is located: http:// 192.168.0.5/app/insert.php
This is the code I have at the moment in 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();
}