Check if POST is succesfull (Android)

1.4k views Asked by At

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();

}
2

There are 2 answers

1
AndroidTestor On BEST ANSWER

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.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
1
mattfred On

Check for response code. Then only get the response if you are getting the correct response code.

int responseCode = conn.getResponseCode();