Untitled
unknown
java
2 years ago
2.5 kB
9
Indexable
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonHttpPostExample {
public static void main(String[] args) {
try {
// Создание URL-адреса, куда будет отправлен запрос
URL url = new URL("http://example.com/api/endpoint");
// Создание соединения
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Установка метода запроса на POST
connection.setRequestMethod("POST");
// Установка заголовков запроса
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// Включение передачи данных
connection.setDoOutput(true);
// Создание JSON-строки для отправки
String jsonInputString = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
// Отправка данных
try (OutputStream outputStream = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
// Получение ответа
int responseCode = connection.getResponseCode();
BufferedReader reader;
if (responseCode >= 200 && responseCode < 300) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
// Чтение ответа
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Вывод ответа
System.out.println(response.toString());
// Закрытие соединения
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Editor is loading...