public void fun(URLConnection connection) { try { connection.connect(); // print header fields Map<String, List<String>> headers = connection.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); for (String value : entry.getValue()) System.out.println(key + ": " + value); } // print convenience functions System.out.println("----------"); System.out.println("getContentType: " + connection.getContentType()); System.out.println("getContentLength: " + connection.getContentLength()); System.out.println("getContentEncoding: " + connection.getContentEncoding()); System.out.println("getDate: " + connection.getDate()); System.out.println("getExpiration: " + connection.getExpiration()); System.out.println("getLastModifed: " + connection.getLastModified()); System.out.println("----------"); Scanner in = new Scanner(connection.getInputStream()); // print first ten lines of contents for (int n = 1; in.hasNextLine() && n <= 10; n++) System.out.println(in.nextLine()); if (in.hasNextLine()) System.out.println(". . ."); } catch (IOException e) { e.printStackTrace(); } }
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(); }