将ArrayList转换为String以传递给Servelet然后转换回来

时间:2016-10-09 00:22:28

标签: java url arraylist urlconnection

这是How to return an iText PDF document to the client side

的延续

我正在尝试将数组传递给Servelet。我被提到Send an Array with an HTTP Get但是,我不明白。这就是我的尝试:

    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));
    }

问题是尝试将Array转换为字符串以传递Servelet:

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

有无数的转换问题;但是没有为此工作。

我也很关心如何将其转换回来,或者在Servelet中使用它。

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

谢谢你,我指出了我正确的方向。经过大量调查后,我发现了以下解决方案。变化:

  1. ArrayList listymAwards = new ArrayList(); to String [] [] listymAwards;以及如何填充
  2. String param1 = Arrays.deepToString(listymAwards);
  3. 当我填充第一个String []时,我需要将[]替换为(),而另一个字符[]确定每行是什么,并分隔行中的每个元素。如果这不正确,请告诉我。