简体   繁体   中英

Sending a POST request in libGDX

How would I go about sending a POST request using libGDX in order to act as if I was logging in?

When I use Postman to send a POST request to my server using IP:8080/login?email=EMAIL&password=12345. It shows the HTML code for the correct page after you login. However when using the below code in libGDX it gives me the main login page. I've tried using setContent with and without the ?. I've tried using a Map that contains email and password and passing that into the setContent with HttpParametersUtils.convertHttpParameters(), but no luck.

I also read a post in regards to sending a POST request with Java that requires you to open the connection first before passing in the parameters. But if this the case I have no idea how to go about it using libGDXs networking methods.

This is currently what I have.

 String URL = "http://IP:8080/login";
    Net.HttpRequest httpPOST = new Net.HttpRequest(Net.HttpMethods.POST);
    httpPOST.setUrl(URL);
    httpPOST.setContent("?email=EMAIL&password=12345");

    Gdx.net.sendHttpRequest(httpPOST, new Net.HttpResponseListener() {
                @Override
                public void handleHttpResponse(Net.HttpResponse httpResponse) {
                    Gdx.app.log("MSG", httpResponse.getResultAsString());
                }

                @Override
                public void failed(Throwable t) {
                    Gdx.app.log("LOGIN", "was NOT successful!");
                }

                @Override
                public void cancelled() {
                    Gdx.app.log("LOGIN", "was cancelled!");
                }
    });

Your content is built like you are sending a GET request and not a POST. The simplest way for you is simply changing Net.HttpMethods.POST to Net.HttpMethods.GET . You are then still sending data to the server, but in the URL. if you want to send it via the http body you have to use POST. But then you have to remove the GET syntax by removing the questionmark ("?").

A good resource for the difference between POST and GET is: https://www.w3schools.com/tags/ref_httpmethods.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM