0

This is a continuation of How to return an iText PDF document to the client side

I am trying to pass an Array to a Servelet. I was referred to Send an Array with an HTTP Get however, I do not understand it. This is what I have tried:

    List<String[]> listymAwards = new ArrayList<String[]>();  
    //...      
    String url = "https://www.awardtracker.org";
    String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
    //String[] param1 = listymAwards.getParameterValues("param1"); // This attempt is not accepted below by URLEncoder.encode(param1, charset), as it is not a String
    String[] param1 = listymAwards.toArray(new String[0]); //This attempt is not accepted below by URLEncoder.encode(param1, charset), as it is not a String

    String param2 = scoutName;
    String param3 = groupName;
    // ...

    String query = String.format("param1=%s&param2=%s&param3=%s",
         URLEncoder.encode(param1, charset), 
         URLEncoder.encode(param2, charset),
         URLEncoder.encode(param3, charset));

    URLConnection connection = new URL(url).openConnection();
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

    try (OutputStream output = connection.getOutputStream()) {
        output.write(query.getBytes(charset));
    }

The issue is trying to convert the Array to string to pass the the Servelet at:

 String[] param1 = listymAwards.toArray(new String[0]); //This attempt is not accepted below by URLEncoder.encode(param1, charset), as it is not a String

There are a myriad of conversion questions; however non have worked for this.

I am also concerned about how I am going to convert it back, or use it, in the Servelet.

Community
  • 1
  • 1
Glyn
  • 1,933
  • 5
  • 37
  • 60

2 Answers2

1

Try this:

String param1 = java.util.Arrays.toString(listymAwards)

i-bob
  • 423
  • 2
  • 5
  • Hi i-bob, the error for this is on toString: "The method toString(long[]) in the type Arrays is not applicable for the arguments (List)" and the quick fixes are; "Change to 'deepToString(...)'" and "Change type of 'listymAwards' to 'long'[]'". Kind regards, Glyn – Glyn Oct 10 '16 at 07:44
0

Thank you i-bob, you pointed me in the right direction. After a lot of investigation I found the following solution. Change:

  1. ArrayList listymAwards = new ArrayList(); to String[][] listymAwards; and how it is populated
  2. String param1 = Arrays.deepToString(listymAwards);

As I populate the first String[] I need to replace [] with () and , with another character as [] determines what each row is and , separates each element in the row. Please let me know if this is incorrect.

Glyn
  • 1,933
  • 5
  • 37
  • 60