I am doing a post request in Android. It should give me a response in the form of a string. Thats what i do to check it. However it gives me an empty string back. It's in the toast message. Am i doing something wrong, any hints for me guys?
private void makePostRequest() throws UnsupportedEncodingException {
SharedPreferences postpreference = this.getSharedPreferences("preferences", MODE_PRIVATE);
String password = postpreference.getString("Password", null);
String username = postpreference.getString("Username", null);
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
String text = "";
BufferedReader reader = null;
try {
// send post data request
URL url = new URL("secreturl but working");
URLConnection conn = url.openConnection();
OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());
streamWriter.write(data);
streamWriter.flush();
//read the response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
// Show response on activity
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
I fixed it following the first solution in this link : Android, Java: HTTP POST Request
Thanks for help
Edit : Correct way to do the post request.