Copy and paste the following class to insert data to mysql database.
If you want to use more POST parameters just concatenate the variable urlParameters with appropriate values and POST variable names.
public class BackgroundWorker extends AsyncTask { private Context context; //in constructor: public BackgroundWorker(Context context){ this.context=context; } @Override protected String doInBackground(String... params) { URL url; HttpURLConnection connection = null; try { //Create connection url = new URL(params[0]); String urlParameters= URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8"); urlParameters += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(params[2], "UTF-8"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream( connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPreExecute() { //super.onPreExecute(); } @Override protected void onPostExecute(String s) { Toast.makeText(context, "Success", Toast.LENGTH_LONG).show(); //super.onPostExecute(s); } }
To call the above class use the following code:
BackgroundWorker backgroundWorker= new BackgroundWorker(this); backgroundWorker.execute("server_url_with_php_file", "param1_value", "param2_value");
Here is the link to the initial stackoverflow problem: http://stackoverflow.com/questions/38317614/http-post-via-android-java-does-not-work/38318341#38318341