简体   繁体   中英

Sending a post request with payload in java

I need to get the content of a file, which I have found with chromes inspector under the.network tab. To achieve this, I want to send a post request with the required payload to the request URL. Since I have used the Selenium ChromeDriver to navigate and log into the page, I first tried using the HtmlRequest class provided by Selenium. But I was stuck after just a few seconds, when I did not know how to pass in the payload or how to execute the request once I would be eventually done. Since I was unable to find a proper explanation or example of this class, I did not get any further than the following code:

HttpRequest xhr = new HttpRequest(HttpMethod.POST, "https://flow.polar.com/api/training/history");
xhr.setContent(?);

Next, I tried using the HttpClient class from java.net.http. I found the following example and changed the URL to the one, the chrome inspector presented me as the request URL.

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://flow.polar.com/api/training/history")).build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();

This returned a html site, which just tells me, that the site with the URL I put in could not be found.

I then tried using the JavascriptExeucutor of Selenium with the following code:

JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("var xhr = new XMLHttpRequest();\r\n" + 
        "xhr.open('POST', 'https://flow.polar.com/api/training/history', false);\r\n" + 
        "xhr.setRequestHeader('XHR', 'application/x-www-form-urlencoded');\r\n" + 
        "\r\n" + 
        "xhr.send('login=test&password=test');\r\n" + 
        "return xhr.response;", (Object) null));

This returns html code, which shows the following website: 网站

It would be really nice to get an answer, because I have spent way too much time trying to figure out a way to do this (multiple attempts with iterations of the code examples above were conducted, however they yielded the same or worse results).

Here are screenshots of the chrome inspector on the wanted file: chromeInspector1

chromeInspector2

The error say all about that. 403 means you are not authorized to POST . That means, You are trying to create a resource without Authorization .

在此处输入图像描述

You need to generate authorization token and use that for your POST request.

Please refer Http Basic Authentication in Java using HttpClient?

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