Check if POST is successful (Android)

I am making a post request in Android. He should give me the answer as a string. What I am doing is to check this. However, it returns me an empty string. It's in the toast message. Am I doing something wrong, any hints at 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();

}

      

+3


source to share


2 answers


I fixed it after the first solution in this link: Android, Java: HTTP POST Request

thanks for the help



Edit: Correct way of doing 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
}

      

0


source


Check the response code. Then you will only get a response if you receive the correct response code.



int responseCode = conn.getResponseCode();

      

0


source







All Articles