Я использую Apache , чтобы создать работоспособный пример POST
запроса
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
...
public static void main(String[] args) throws IOException {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://reqres.in/api/register");
// Simple data
httppost.setEntity(
new StringEntity("{\"email\":\"eve.holt@reqres.in\",\"password\":\"pistol\"}",ContentType.create("application/json", StandardCharsets.UTF_8)));
// Simple Header
httppost.setHeader("cache-control", "no-cache");
// Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("Status: " + response.getStatusLine().toString());
if (entity != null) {
try (InputStream instream = entity.getContent()) {
System.out.println("response: " + IOUtils.toString(instream, StandardCharsets.UTF_8));
}
}
}
Ответ от System.out.println()
Статус: HTTP / 1.1 200 OK
ответ: {"id": 4, "token": "QpwL5tke4Pnpja7X4"}