1

I want to send multiple values in one key, like sendTo[] -string array and values comma separated in that like abcd@gmail.com,pqrs@gmail.com.

This I tried to achieve using string builder, appended all values using comma separated and then add the builder in hash map with the key.

Like this :

 StringBuilder emailbuilder = new StringBuilder();
                    for (String mail : mEmailList) {

                        emailbuilder.append(mail+",");
                        i++;
                    }

    data.put("send_to[]", emailbuilder.toString());

So it results in hashmap as abcd@gmail.com,pqrs@gmail.com, -- string like this gets added as value for key send_to[].

Later, the type of data sending is x-www-form-urlencoded, so I am converting data into that format.

function to convert :

 private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (first)
            first = false;
        else
            result.append("&");
        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }
    return result.toString();
}

But, after converting it converts the values too. The send_to[] key , value becomes like ---&send_to%5B%5D=realdammy%40hotmail.com%2Csiddhijambhale%40gmail.com%2C

It converts brackets and comma into % format. I need to send data like --- send_to key and value abcd@gmail.com,pqrs@gmail.com

How can I achieve this? Please help Thank you...

EDIT: The function to run the request.

public String sendPostRequest(String data) {

    try {

        URL url = new URL(api);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        con.setDoOutput(true);
        con.setDoInput(true);
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

        try {
            writer.write(data);
        } catch (Exception e) {
            Log.e("Exception111", e.toString());
        }

        writer.close();

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            Log.d("ServerResponse", new String(sb));
            String output = new String(sb);
            return output;
        } else {
            Log.e("Exception", "" + responseCode);
        }
    }
    catch(IOException e)
    {
        Log.e("Exception", "" + e.toString());
    }
    return null;
}
Sid
  • 2,792
  • 9
  • 55
  • 111

2 Answers2

0

As you are sending the values in a GET request, what you are trying to achieve is not possible. The values will be anyway encoded into % forms to be sent with a GET request. It can be only done if you send the values in a POST request.

To answer in the current context, You need to do a URLDecode at the backend to get the values in that form.

It's a very normal thing and may doesn't even required any additional backend programming. You should receive the same abcd@gmail.com,pqrs@gmail.com easily

Let me know if this worked...

EDIT 1:

Normally we use libraries like Volley for these stuffs..

But to do this with HttpURLConnection, use the following method to prepare Data String

private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (first)
            first = false;
        else
            result.append("\n");
        result.append(entry.getKey());
        result.append(":");
        result.append(entry.getValue());
    }
    return result.toString();
}

Use the following method to add email to the data

data.put("sent_to", TextUtils.join(",",mEmailList));

Keep me posted...

rex
  • 421
  • 4
  • 12
  • This is not a GET request its a POST request having content type x-www-urlencoded. – Sid Oct 02 '17 at 06:18
  • Well I'm not sure if sending in this format would make the server receive it. But if the server is getting the data from you and you are concerned only about the format. You can skip using URLEncoder and it should work. – rex Oct 02 '17 at 06:33
  • I dont know if server receiving it right because I get response code 500, some exception. How can I send this? Can you give some example please? Thank you. – Sid Oct 02 '17 at 06:39
  • Its not working, I am not able to send the array, the values separated by comma, its considered as single value not different values. – Sid Oct 04 '17 at 14:41
0

You can use volley https://github.com/google/volley.

String tag_json_obj = "json_obj_req";

String url = "your url";

ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();     

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                params.put("send", "abc@gmail.info,abc1@gmail.info");
                params.put("password", "password123");

                return params;
            }

        };

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
Rajesh N
  • 6,198
  • 2
  • 47
  • 58