I'm new to Android development, and I need to send a pretty basic HTTP POST request to a PHP server, and came across this method:
protected void performRequest(String name, String pn) {
String POST_PARAMS = "name=" + name + "&phone_number=" + pn;
URL obj = null;
HttpURLConnection con = null;
try {
obj = new URL("theURL");
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// For POST only - BEGIN
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
Log.i(TAG, "POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Log.i(TAG, response.toString());
} else {
Log.i(TAG, "POST request did not work.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
But when I run this the app crashes, saying:
FATAL EXCEPTION: main
Process: (the app id), PID: 11515
android.os.NetworkOnMainThreadException
As much as I understood, I need to perform this on a background thread, is there a relatively simple way to do it?
Also, I've seen a method to send post request using HttpClient, but it seems to be deprecated. Is it still usable nonetheless?
Thanks in advance!