Comment utiliser java.net. URLConnection pour tirer et gérer les requêtes HTTP

Mots clés : javahttphttprequesthttpurlconnectionjava

meilleur 4 Réponses Comment utiliser java.net. URLConnection pour tirer et gérer les requêtes HTTP

vote vote

99

String url = "http://example.com"; String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name() String param1 = "value1"; String param2 = "value2"; // ...  String query = String.format("param1=%s&param2=%s",     URLEncoder.encode(param1, charset),     URLEncoder.encode(param2, charset)); 
URLConnection connection = new URL(url + "?" + query).openConnection(); connection.setRequestProperty("Accept-Charset", charset); InputStream response = connection.getInputStream(); // ... 
InputStream response = new URL(url).openStream(); // ... 
try (Scanner scanner = new Scanner(response)) {     String responseBody = scanner.useDelimiter("\\A").next();     System.out.println(responseBody); } 
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)); }  InputStream response = connection.getInputStream(); // ... 
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod("POST"); // ... 
    int status = httpConnection.getResponseCode(); 
 for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {      System.out.println(header.getKey() + "=" + header.getValue());  } 
    String contentType = connection.getHeaderField("Content-Type");     String charset = null;      for (String param : contentType.replace(" ", "").split(";")) {         if (param.startsWith("charset=")) {             charset = param.split("=", 2)[1];             break;         }     }      if (charset != null) {         try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {             for (String line; (line = reader.readLine()) != null;) {                 // ... System.out.println(line)?             }         }     } else {         // It's likely binary content, use InputStream/OutputStream.     } 
// First set the default cookie manager. CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));  // All the following subsequent URLConnections will use the same cookie manager. URLConnection connection = new URL(url).openConnection(); // ...  connection = new URL(url).openConnection(); // ...  connection = new URL(url).openConnection(); // ... 
// Gather all cookies on the first request. URLConnection connection = new URL(url).openConnection(); List<String> cookies = connection.getHeaderFields().get("Set-Cookie"); // ...  // Then use the same cookies on all subsequent requests. connection = new URL(url).openConnection(); for (String cookie : cookies) {     connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } // ... 
httpConnection.setFixedLengthStreamingMode(contentLength); 
httpConnection.setChunkedStreamingMode(1024); 
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7. 
InputStream error = ((HttpURLConnection) connection).getErrorStream(); 
System.setProperty("http.keepAlive", "false"); 
String param = "value"; File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. String CRLF = "\r\n"; // Line separator required by multipart/form-data. URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);  try (     OutputStream output = connection.getOutputStream();     PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); ) {     // Send normal param.     writer.append("--" + boundary).append(CRLF);     writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);     writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);     writer.append(CRLF).append(param).append(CRLF).flush();      // Send text file.     writer.append("--" + boundary).append(CRLF);     writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);     writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!     writer.append(CRLF).flush();     Files.copy(textFile.toPath(), output);     output.flush(); // Important before continuing with writer!     writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.      // Send binary file.     writer.append("--" + boundary).append(CRLF);     writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);     writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);     writer.append("Content-Transfer-Encoding: binary").append(CRLF);     writer.append(CRLF).flush();     Files.copy(binaryFile.toPath(), output);     output.flush(); // Important before continuing with writer!     writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.      // End of multipart/form-data.     writer.append("--" + boundary + "--").append(CRLF).flush(); } 
static {     TrustManager[] trustAllCertificates = new TrustManager[] {         new X509TrustManager() {             @Override             public X509Certificate[] getAcceptedIssuers() {                 return null; // Not relevant.             }             @Override             public void checkClientTrusted(X509Certificate[] certs, String authType) {                 // Do nothing. Just allow them all.             }             @Override             public void checkServerTrusted(X509Certificate[] certs, String authType) {                 // Do nothing. Just allow them all.             }         }     };      HostnameVerifier trustAllHostnames = new HostnameVerifier() {         @Override         public boolean verify(String hostname, SSLSession session) {             return true; // Just allow them all.         }     };      try {         System.setProperty("jsse.enableSNIExtension", "false");         SSLContext sc = SSLContext.getInstance("SSL");         sc.init(null, trustAllCertificates, new SecureRandom());         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());         HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);     }     catch (GeneralSecurityException e) {         throw new ExceptionInInitializerError(e);     } } 
vote vote

88

int responseCode = httpURLConnection.getResponseCode();  if (responseCode == HttpURLConnection.HTTP_OK) { 
vote vote

77

// GET http://google.com?q=baseball%20gloves&size=100 String response = HttpRequest.get("http://google.com", true, "q", "baseball gloves", "size", 100)         .accept("application/json")         .body(); System.out.println("Response was: " + response); 
vote vote

61

// GET HttpResponse response = HttpRequest     .create(new URI("http://www.stackoverflow.com"))     .headers("Foo", "foovalue", "Bar", "barvalue")     .GET()     .response(); 
int statusCode = response.statusCode(); String responseBody = response.body(HttpResponse.asString()); 
module com.foo.bar {     requires jdk.incubator.httpclient; } 

Questions similaires