1

I have a web backend, which works with the following jQuery post:

$.post(path + "login",
       {"params": {"mode":"self", "username": "aaa", "password": "bbb"}},
       function(data){
                console.log(data);
            }, "json");

How can I implement the same POST from Java, with HttpURLConnection? I'm trying with

URL url = new URL(serverUrl + loginUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length",
    Integer.toString(postData.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr =
    new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(postData);
wr.flush ();
wr.close ();
BufferedReader br =
    new BufferedReader(
        new InputStreamReader(connection.getInputStream()));

, where postData = "{\"mode\": \"...\", ..... }"

but it doesn't work the same way.

The code on the server is written id Django, and tries to get the data in this way:

mode=request.POST.get("params[mode]")
Jason Aller
  • 3,391
  • 28
  • 37
  • 36
Nagy Vilmos
  • 1,738
  • 18
  • 41
  • What do you mean _doesn't work the same_? What do you want it to do? What does it do instead? – Sotirios Delimanolis Aug 20 '14 at 17:44
  • It posts some data to a webserver, and I want to get the response as string. It works, when I try to use it with an HTML page with the jQuery function above. But I cannot re-create the same post request from Java. – Nagy Vilmos Aug 20 '14 at 17:47
  • It gives back HTTPError 500, 'cause the code on the server can't get the data from the request, it want... – Nagy Vilmos Aug 20 '14 at 17:53

2 Answers2

1

You seem to be thinking all the time that jQuery sends JSON in its raw form to the server and that the HTTP server flawlessly understands it. This is not true. The default format for HTTP request parameters is application/x-www-form-urlencoded, exactly like as HTML forms in HTTP websites are using and exactly like as how GET query strings in URLs look like: name1=value1&name2=value2.

In other words, jQuery doesn't send JSON unmodified to the server. jQuery just transparently converts them to true request parameters. Pressing F12 in a sane browser and inspecting the HTTP traffic monitor should also have shown you that. The "json" argument which you specified there in end of $.post just tells jQuery which data format the server returns (and thus not which data format it consumes).

So, just do exactly the same as jQuery is doing under the covers:

String charset = "UTF-8";
String mode = "self";
String username = "username";
String password = "bbb";
String query = String.format("%s=%s&%s=%s&%s=%s",
    URLEncoder.encode("param[mode]", charset), URLEncoder.encode(mode, charset),
    URLEncoder.encode("param[username]", charset), URLEncoder.encode(username, charset),
    URLEncoder.encode("param[password]", charset), URLEncoder.encode(password, charset));

// ... Now create URLConnection.

connection.setDoOutput(true); // Already implicitly sets method to 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));
}

// ... Now read InputStream.

Note: do NOT use Data(Input|Output)Stream! Those are for creating/reading .dat files.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
-1

You should use efficient libraries to build (valid) json objects. Here is an example from the PrimeFaces library:

private JSONObject createObject() throws JSONException {
    JSONObject object = new JSONObject();
    object.append("mode", "...");
    return object;
}

If you wish to have a nice and clean code to send and retrieve objects, take a look at the answer from Emil Adz ( Sending Complex JSON Object ).

Community
  • 1
  • 1
Ioannis K.
  • 532
  • 1
  • 5
  • 19