Клиент (Java). Выполняется jar на компьютере
static void addToBd(String name, String year, String quality, String genre, String duration, String ozvuchka, String country, String cast, String producer, String description, String download, String art, String screenshots){
try
{
String jsonResponse;
URL url = new URL("http://<некий адрес>/<некий скрипт>.php?");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestMethod("POST");
JSONObject film = new JSONObject();
film.put("name", name);
film.put("year", year);
film.put("quality", quality);
film.put("genre", genre);
film.put("duration", duration);
film.put("ozvuchka", ozvuchka);
film.put("country", country);
film.put("cast", cast);
film.put("producer", producer);
film.put("description", description);
film.put("download", download);
film.put("art", art);
film.put("screenshots", screenshots);
String strJsonBody = "json="+film.toString();
System.out.println("strJsonBody: " + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if (httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST)
{
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
else
{
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("Response: " + jsonResponse);
}
catch (Throwable t)
{
t.printStackTrace();
}
finally
{
return;
}
}
Сервер
<?php
$servername = ":)";
$username = ":)";
$password = ":)";
$conn = new mysqli($servername, $username, $password);
$conn -> query("USE admin_filmsanwap");
$conn->set_charset("utf8");
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$data = $_POST['json'];
$result = json_decode($data);
$name = $result->name;
$year = $result->year;
$quality = $result->quality;
$genre = $result->genre;
$duration = $result->duration;
$ozvuchka = $result->ozvuchka;
$country = $result->country;
$cast = $result->cast;
$producer = $result->producer;
$description = $result->description;
$download = $result->download;
$art = $result->art;
$screenshots = $result->screenshots;
$insert = "INSERT INTO `admin_filmsanwap`.`films` (`name`,`year`,`quality`,`genre`,`duration`,`ozvuchka`,`country`,`cast`,`producer`,`description`,`download`,`art`,`screenshots`) VALUES ('$name', '$year', '$quality', '$genre', '$duration', '$ozvuchka', '$country', '$cast', '$producer', '$description', '$download', '$art', '$screenshots');";
if(mysqli_query($conn, $insert)){
echo 'success';
}
else {
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
}
?>
Ответ от сервера
strJsonBody: json={"name":"t","year":"t","quality":"t","genre":"t","duration":"t","ozvuchka":"t","country":"t","cast":"t","producer":"t","description":"t","download":"t","art":"t","screenshots":"t"}
httpResponse: 200
Response: success
Почему в БД добавляется запись с пустыми колонками? Где ошибка? Будет ли работать UTF-8?
Зачем Вам смешивать два формата?
Вы сообщаете в запросе что отсылаете данные в формате application/json, а шлёте вы их в формате multipart/form-data.
Замените в Java-клиенте тело запроса
String strJsonBody = "json="+film.toString();
на
String strJsonBody = film.toString();
И в php его получение: замените:
$data = $_POST['json'];
$result = json_decode($data);
на следующие строки:
$data = file_get_contents("php://input");
$result = json_decode($data);
Как развивать веб-проекты в 2026 году: технологии, контент E-E-A-T и факторы доверия
Современные инструменты для криптотрейдинга: как технологии помогают принимать решения
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники