'Content Type issue in http requests (still text/html when I change it to application/json)
I try to write a service in PHP and my code does not work.
This is my code
<?php
$data_array = array();
$data_file_contents = file_get_contents("../data/credentials.txt");
$u_p = explode(" ", $data_file_contents);
$host=$u_p[0];
$uname=$u_p[1];
$pass=$u_p[2];
$dbname=$u_p[3];
$dbh = mysqli_connect($host,$uname,$pass) or die("cannot connect");
mysqli_select_db($dbh, $dbname);
mysqli_close($dbh);
$data_array['host'] = $host;
$data_array['username'] = $uname;
$data_array['password'] = $pass;
$data_array['dbname'] = $dbname;
$data = json_encode($data_array);
header("Content-Type: application/json");
echo $data;
exit();
?>
The output is correct and in json format as I want but the response in an HTTP request in reqbin for example is this:
Server: nginx
Date: Wed, 18 May 2022 19:56:16 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Expires: Thu, 01 Jan 1970 00:00:01 GMT
Cache-Control: no-cache
Content-Encoding: gzip
This is some java code to see if that works but it doesn't
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class http{
public static void main(String[] args) throws IOException{
URL url = new URL("http://myAddress/service.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
String contentType = con.getContentType();
System.out.println("Content Type: " + contentType);
con.disconnect();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
