0

I'm trying to post a an HTTP URL with parameters. I've appended the parameters using appendQueryPrameters But statements after build() are skipped and the control comes out of the AsyncTask.Below is th snippet of the AsyncTask

private class MyAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub


            String givenDob = params[0];
            String givensurname = params[1];
            String givenCaptcha = params[2];
            String response = "";
            try {
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("dateOfBirth", givenDob)
                        .appendQueryParameter("userNameDetails.surName", givensurname)
                        .appendQueryParameter("captchaCode", givenCaptcha);
                String query = builder.build().toString();
                PrintWriter out = new PrintWriter(connection.getOutputStream());
                out.print(query);
                out.close();
                int responseCode = connection.getResponseCode();
                Log.d("responseCode", String.valueOf(responseCode));

   /*             BufferedWriter writer = new BufferedWriter(
                      new OutputStreamWriter(connection.getOutputStream(), "ISO-8859-1"));

                writer.write(query);
               writer.flush();
               writer.close();
    */
                connection.getOutputStream().close();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;

                        Log.d("response", response);
                    }
                } else {
                    response = "";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


            return response;
        }

        @Override
        protected void onPostExecute(String s) {
            Log.d("res", s);
        }

    }

I tried with PrintWriter also.Still it skips the execution of the statements after the line String query = builder.build().toString();

PS: I've opened the HttpURLconnection in another AsyncTask and calling that on onCreate() Below is the code.

 URL url = new URL("https://myurl.com/path1/path2/path3.html");
            connection = (HttpsURLConnection) url.openConnection();
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);

Used this for reference

Community
  • 1
  • 1
BlushMaq
  • 15
  • 7

2 Answers2

1

I will tell you what i do to send parameters to my server using HttpURLConnection object:

            // Instantiate the connexion.
            URL url = new URL(_url);
            HttpURLConnection con;


            // Build data string to send to server:
            String data = StringUtils.paramsToUrlString(params);

            /* Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.*/
            con = (HttpURLConnection)url.openConnection();
            // Activar método POST:
            // Instances must be configured with setDoOutput(true) if they include a request body.
            con.setDoOutput(true);
            // Data size known:
            con.setFixedLengthStreamingMode(data.getBytes("UTF-8").length);
            // Establecer application/x-www-form-urlencoded debido a la simplicidad de los datos
            //con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // NO SIRVE PARA UTF-8
            con.setRequestProperty("Accept-Charset", "UTF-8");
            con.getContentEncoding();

            // Set time out for both reading and writing operations.
            con.setConnectTimeout(30*1000);
            con.setReadTimeout(30*1000);

            // Read the response:
            // Upload a request body: Write data on the output stream (towards the server)
            OutputStream out = new BufferedOutputStream(con.getOutputStream());
            out.write(data.getBytes("UTF-8"));
            out.flush();
            out.close();

            // Store the input stream (server response):
            // If the response has no body, that method returns an empty stream.
            is = new BufferedInputStream(con.getInputStream());

            // Return JSON Object.
            jObj = castResponseToJson(is);

            // Disconnect: Release resources.
            con.disconnect();

And StringUtils.paramsToUrlString(params) is the method that converts the parameters into a suitable URL string:

/**
 * This method receives a ContentValues container with the parameter
 * and returns a well formed String to send the parameter throw Hppt.
 *
 * @param params Parameter to send to the server.
 * @return param1=param1value&param2=param2value&....paramX=paramXvalue.
 */
public static String paramsToUrlString (ContentValues params) {

    String data = "";

    Set<Map.Entry<String, Object>> s = params.valueSet();
    Iterator itr = s.iterator();

    Log.d("Constructing URL", "ContentValue Length : " + params.size());

    while(itr.hasNext())
    {
        Map.Entry me = (Map.Entry)itr.next();
        String key = me.getKey().toString();
        String value =  me.getValue().toString();

        try {
            data+=(URLEncoder.encode(key, "UTF-8")+"="+URLEncoder.encode(value, "UTF-8")+"&");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    // Removing last char from data:
    return (data.substring(0, data.length()-1));
}

The parameters received by paramsToUrlString(params) method must be contained on a ContentValues Object like this:

    ContentValues params = new ContentValues();
    params.put("Param1Name", "Param1Value");
    params.put("Param2Name", "Param2Value");
    params.put("Param3Name", "Param3Value");
ÁngelBlanco
  • 438
  • 4
  • 11
  • Sir,appreciate your answer. I can always opt for this. But I'm new to android development. So want a code that's as small as possible and easy to read. – BlushMaq Jan 27 '16 at 11:28
0
 URL strUrl = new URL("https://myurl.com/path1/path2/path3.html?dateOfBirth=" + params[0] +
                    "&userNameDetails.surName=" + params[1] +
                    "&captchaCode=" + params[2]);

            Log.d("strUrl", String.valueOf(strUrl));

            URLConnection conn = strUrl.openConnection();

[This code serves the purpose after a small change. But unforutnately OP of this answer deleted his comment.]

Edit: Actually I'm opening connection to fetch the captcha . Using above method makes me open another connection which is getting me a wrong captcha error. So This is not the answer.

Edit2: Using cookimanager helped me. Here' more https://stackoverflow.com/a/35104167/5733855

Community
  • 1
  • 1
BlushMaq
  • 15
  • 7