Mulgard
Mulgard

Reputation: 10609

DefaultHttpClient and HttpPost deprecated, using HttpURLConnection POST but getting ERROR: WRONG PARAMETERS

Right now I'm fighting with the HttpURLConnection class. Earlier I simply did this:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

return httpEntity.getContent();

But since nearly everything of that is deprecated I decided that I have to change that. I tried to replace it with the following code:

/**
 * 
 * @param urlString
 * @param params
 * @return
 * @throws IOException
 */
public InputStream getStreamFromConnection(String urlString, ContentValues params) throws IOException {
    HttpURLConnection connection = null;

    if(ConnectionDetector.isConnectedToInternet(this.context)) {
        try {
            StringBuilder urlBuilder = new StringBuilder(urlString);
            StringBuilder paramsBuilder = new StringBuilder();

            int i = 0;

            for (String key : params.keySet()) {
                paramsBuilder.append((i == 0 ? "" : "&") + key + "=" + URLEncoder.encode(params.get(key).toString(), "utf8"));
                i++;
            }

            Log.v("Connection", "This is my URL: " + urlBuilder.toString());

            URL url = new URL(urlBuilder.toString());

            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setChunkedStreamingMode(0);

            Log.v("Connection", "These are my Params: " + paramsBuilder.toString());

            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(paramsBuilder.toString().getBytes());
            outputStream.flush();
            outputStream.close();

            return connection.getInputStream();
        } finally {
            if(connection != null) {
                connection.disconnect();
            }
        }
    } else {
        return null;
    }
}

But now I always get the message from the server that my parameters are wrong. Isn't my new code the exact same thing like my old code? What could be wrong with my parameters? Is there a function so that I can see the whole url string sent to the server?

8366-8599/de.myPackage.myApp V/Connection﹕ This is my URL: http://myUrl.com/mobile_login.php
8366-8599/de.myPackage.myApp V/Connection﹕ These are my Params: email=my%40email.com&password=B5FDA3381CDE21D59843ACC16572127F45078770A331D9BE9085719A5BD35ACF46D&login_request=1
8366-8599/de.myPackage.myApp V/Connection﹕ ERROR: WRONG PARAMETERS
8366-8599/de.myPackage.myApp V/JSONParser﹕ [ 07-27 20:18:39.469  8366: 8599 V/JSONParser ]

Upvotes: 0

Views: 911

Answers (1)

Daniel Nugent
Daniel Nugent

Reputation: 43342

It's hard to tell exactly what is going wrong in your code, but I just got this simple example working with email, password, and login_request parameters.

First, here's the method with the HttpURLConnection:

public JSONObject makeHttpRequest(String url,
                                  HashMap<String, String> params) {

    StringBuilder sbParams = new StringBuilder();
    StringBuilder result = new StringBuilder();
    String charset = "UTF-8";
    HttpURLConnection conn = null;
    JSONObject jObj = null;
    URL urlObj = null;
    DataOutputStream wr = null;

    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0){
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    Log.d("HTTP Request", "params: " + sbParams.toString());

    try {
        urlObj = new URL(url);

        conn = (HttpURLConnection) urlObj.openConnection();

        conn.setDoOutput(true);

        conn.setRequestMethod("POST");

        conn.setRequestProperty("Accept-Charset", charset);

        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);

        conn.connect();

        String paramsString = sbParams.toString();

        wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(paramsString);
        wr.flush();
        wr.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("HTTP Request", "result: " + result.toString());

    } catch (IOException e) {
        e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(result.toString());
    } catch (JSONException e) {
        Log.e("HTTP Request", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}

Here's the AsyncTask I used for testing the above method:

class PostAsyncTest extends AsyncTask<String, String, JSONObject> {

    private ProgressDialog pDialog;

    private static final String LOGIN_URL = "http://www.example.com/testPost.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";


    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

        try {
            HashMap<String, String> params = new HashMap<>();
            params.put("email", args[0]);
            params.put("password", args[1]);
            params.put("login_request", args[2]);

            JSONObject json = makeHttpRequest(
                    LOGIN_URL, params);

            if (json != null) {
                Log.d("HTTP Async", "JSON result: " + json.toString());

                return json;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(JSONObject json) {

        int success = 0;
        String message = "";

        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (json != null) {
            Toast.makeText(MainActivity.this, json.toString(),
                    Toast.LENGTH_LONG).show();

            try {
                success = json.getInt(TAG_SUCCESS);
                message = json.getString(TAG_MESSAGE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (success == 1) {
            Log.d("HTTP Async", "Success! " +  message);
        }else{
            Log.d("HTTP Async", "Failure " + message);
        }
    }

}

Here's how I executed the AsyncTask:

    String email = "[email protected]";
    String password = "myPasswordIsVery5ecur3";
    String loginRequest = "1";
    new PostAsyncTest().execute(email, password, loginRequest);

Here is the simple PHP code I used to test:

<?php

  // array for JSON response
$response = array();

// check for required fields
if (isset($_POST['email']) && isset($_POST['password']) && isset($_POST['login_request'])) {

    $name = $_POST['email'];
    $message = $_POST['password'];
    $loginrequest = $_POST['login_request'];

    $response["success"] = 1;
    $response["message"] = "Login successful.";

    // echoing JSON response
    print(json_encode($response));


 } else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) missing";

    // echoing JSON response
    print(json_encode($response));
}
?> 

And, the result:

 D/HTTP Request﹕ params: password=myPasswordIsVery5ecur3&email=my_email%40example.com&login_request=1
 D/HTTP Request﹕ result: {"success":1,"message":"Login successful."}
 D/HTTP Async﹕ JSON result: {"message":"Login successful.","success":1}
 D/HTTP Async﹕ Success! Login successful.

Upvotes: 3

Related Questions