3

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

}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • isn't it sufficient to just check for the responsecode? – nafas Jun 09 '15 at 15:08
  • Probably, but that is not the problem here... Problem is that i dont get responsecode :) – AndroidTestor Jun 09 '15 at 15:11
  • I don't see where you are making a proper HTTP request here? – Gyro Gearless Jun 09 '15 at 15:14
  • @AndroidTestor - how do you know that? Your code doesn't even check for a response code! Hint: `conn.getResponseCode()` – Stephen C Jun 09 '15 at 15:17
  • Sorry @StephenC, i read your comment to quickly. Indeed i am wrong in this case. however when i do conn.getResponseCode(), the application crashes. i try to put breakpoint in debugger on that line but crashes so quickly, doesn't even generate it. – AndroidTestor Jun 09 '15 at 17:54
  • And what is the exception? Ah! I see. You are squashing the exceptions. Bit of a "foot shot" there .... – Stephen C Jun 09 '15 at 22:23

2 Answers2

0

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

int responseCode = conn.getResponseCode();
mattfred
  • 2,689
  • 1
  • 22
  • 38
  • i do that, then i try to display in toast but the application crashes. Is it not logic to put that in the Toast? In my opinion it should display the response. The app crashes that quickly, doesnt even generate stacktrace. – AndroidTestor Jun 09 '15 at 17:52
0

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
}
Community
  • 1
  • 1