This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: How do I start and process HTTP requests using java.net.URLConnection?

The use of java.net.URLConnection is often asked here, and the Oracle tutorial is too succinctly describing it.

This tutorial basically just shows how to start a GET request and read the response. It doesn’t explain anywhere how to use it to perform POST requests, set request headers, read response headers, process cookies, submit HTML forms, upload files, and so on.

So how do you use java.net.URLConnection to fire up and process “advanced” HTTP requests?

Answer 1:

Use arrays.tostring (arr) or arrays.deepToString (arr) to print Arrays in Java 5+ above. Note that the Object[] version calls.toString() for each Object in the array. The output is even decorated the way you want it to be.

🌰 Here are some chestnuts:

Simple array

String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
Copy the code

Output:

[John, Mary, Bob]
Copy the code

Nested array

String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
Copy the code

Output:

[[John, Mary], [Alice, Bob]]
Copy the code

A double array

Double [] doubleArray = {7.0, 9.0, 5.0, 1.0, 3.0}; System.out.println(Arrays.toString(doubleArray));Copy the code

Output:

[7.0, 9.0, 5.0, 1.0, 3.0]Copy the code

An array of int

int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
Copy the code

Output:

[7, 9, 5, 1, 3]Copy the code

Answer 2:

Always check the introduction of the library first

import java.util.Arrays;
Copy the code

Then try to output:

System.out.println(Arrays.toString(array));
Copy the code

Or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));
Copy the code

provenance

Stack Overflow :How to Use java.net.URLConnection to Fire and handle HTTP requests?