Exemplo n.º 1
0
  public static String doPost(String urlString, Map<Object, Object> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    String encoding = connection.getContentEncoding();
    if (encoding == null) encoding = "ISO-8859-1";

    try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
      boolean first = true;
      for (Map.Entry<Object, Object> pair : nameValuePairs.entrySet()) {
        if (first) first = false;
        else out.print('&');
        String name = pair.getKey().toString();
        String value = pair.getValue().toString();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, encoding));
      }
    }

    StringBuilder response = new StringBuilder();
    try (Scanner in = new Scanner(connection.getInputStream(), encoding)) {
      while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
      }
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      Scanner in = new Scanner(err);
      response.append(in.nextLine());
      response.append("\n");
    }

    return response.toString();
  }
Exemplo n.º 2
0
  public static void main(String args[]) throws IOException {
    try {
      Scanner in = args.length == 0 ? new Scanner(System.in) : new Scanner(Paths.get(args[0]));

      try (Connection conn = getConnection()) {
        Statement stat = conn.createStatement();

        while (true) {
          if (args.length == 0) System.out.println("Enter command or EXIT to exit:");

          if (!in.hasNextLine()) return;

          String line = in.nextLine();
          if (line.equalsIgnoreCase("EXIT")) return;
          if (line.trim().endsWith(";")) // remove trailing semicolon
          {
            line = line.trim();
            line = line.substring(0, line.length() - 1);
          }
          try {
            boolean isResult = stat.execute(line);
            if (isResult) {
              ResultSet rs = stat.getResultSet();
              showResultSet(rs);
            } else {
              int updateCount = stat.getUpdateCount();
              System.out.println(updateCount + " rows updated");
            }
          } catch (SQLException ex) {
            for (Throwable e : ex) e.printStackTrace();
          }
        }
      }
    } catch (SQLException e) {
      for (Throwable t : e) t.printStackTrace();
    }
  }