【问题标题】:Convert an ArrayList to a String to pass to Servelet and then convert back将 ArrayList 转换为 String 以传递给 Servlet,然后再转换回来
【发布时间】:2016-10-09 00:22:28
【问题描述】:

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

我正在尝试将数组传递给 Servlet。我被提到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 中将其转换回或使用它。

【问题讨论】:

    标签: java url arraylist urlconnection


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 嗨 i-bob,toString 上的错误是:“数组类型中的方法 toString(long[]) 不适用于参数 (List)”和快速修复是; “更改为 'deepToString(...)'”和“将 'listymAwards' 的类型更改为 'long'[]'”。亲切的问候,格林
    【解决方案2】:

    谢谢 i-bob,你为我指明了正确的方向。经过大量调查,我找到了以下解决方案。变化:

    1. ArrayList listymAwards = new ArrayList();到 String[][] listymAwards;以及如何填充
    2. String param1 = Arrays.deepToString(listymAwards);

    当我填充第一个 String[] 时,我需要将 [] 替换为 () 并且 用另一个字符作为 [] 确定每一行是什么,并且分隔行中的每个元素。如果这不正确,请告诉我。

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 2013-11-15
      • 2017-01-02
      • 2011-02-15
      • 2015-01-05
      • 2020-04-02
      • 2014-03-18
      • 1970-01-01
      • 2011-08-20
      相关资源
      最近更新 更多