Клиент (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);
Кофе для программистов: как напиток влияет на продуктивность кодеров?
Рекламные вывески: как привлечь внимание и увеличить продажи
Стратегії та тренди в SMM - Технології, що формують майбутнє сьогодні
Выделенный сервер, что это, для чего нужен и какие характеристики важны?
Современные решения для бизнеса: как облачные и виртуальные технологии меняют рынок
Не могу разобраться как часть кода разместить в другом классе и потом получить к нему доступ
При записи из JTable в Excel постоянно создается новый файл с xls, вместо создания новых листовК примеру :
Есть класс MainActivity из которого запускаю другой класс, через startintent, допустим, TwoActivityНо TwoActivity не видит интерфейс, то есть findViewById не видит ID элементов...