Table of contents

HttpURLConnection request array or json data

Java HttpURLConnection Mar 16, 2020 Viewed 90 Comments 0

Using Java's HttpURLconnection request, GET or POST method. You can submit an array or json to the server.

Get method

Refer to Java HttpURLConnection GET Request

try {
    StringBuilder sb = new StringBuilder();
    sb.append(URLEncoder.encode("arr[0]", "UTF-8"));
    sb.append("=");
    sb.append(URLEncoder.encode("test0", "UTF-8"));
    sb.append("&");
    sb.append(URLEncoder.encode("arr[1]", "UTF-8"));
    sb.append("=");
    sb.append(URLEncoder.encode("test1", "UTF-8"));
    HttpGet multipart = new HttpGet("http://localhost?" + sb.toString(), "utf-8");
    // Get the result
    String response = multipart.finish();
    System.out.println(response);
} catch (Exception e) {
    e.printStackTrace();
}

Post method

Using post method, there are three ways.

text/plain

Parse the array into a json string and store it in the http body. The server will receive a string of text and you need to encode the text.

Refer to HttpURLConnection post raw data

try {
    HttpPostRaw postRaw = new HttpPostRaw("http://localhost/test.php", "utf-8");
    String arr = "{\"arr\": [1, 2]}";
    postRaw.setPostData(arr);
    postRaw.addHeader("Content-Type", "application/json");
    String out = postRaw.finish();
    System.out.println(out);
} catch (Exception e) {
    e.printStackTrace();
}

multipart/form-data

Refer to  HttpURLConnection multipart/form-data example

try {
    // Add header
    Map<String, String> headers = new HashMap<>();
    headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36");
    HttpPostMultipart multipart = new HttpPostMultipart("http://localhost/test.php", "utf-8", headers);
    multipart.addFormField("arr[0]", "1");
    multipart.addFormField("arr[1]", "2");
    String out = multipart.finish();
    System.out.println(out);
} catch (Exception e) {
    e.printStackTrace();
}

In this way, it is similar to the use of javascript arrays.

var arr = [];
arr[0] = 1;
arr[1] = 2;
console.log(arr);

application/x-www-form-urlencoded

Refer to  HttpURLConnection application/x-www-form-urlencoded sample

Send a two-dimensional array to the server.

try {
    HttpPostForm form = new HttpPostForm("http://localhost/test.php", "utf-8");
    form.addFormField("arr[0][0]", "00");
    form.addFormField("arr[0][1]", "01");
    form.addFormField("arr[1][0]", "10");
    form.addFormField("arr[1][1]", "11");
    String out = form.finish();
    System.out.println(out);
} catch (Exception e) {
    e.printStackTrace();
}
Updated Mar 16, 2020