<?php
$curl = curl_init ();
$headers = array (
"Content-Type: application/json",
"ulogin : abc",
"Authorization : abcdefgh"
);
curl_setopt ( $curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $curl, CURLOPT_URL, "http://localhost:8080/api/orders/209");
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec ( $curl );
if ($result === false) {
die ( 'Error fetching data: ' . curl_error ( $curl ) );
} else {
var_dump ( $result );
}
curl_close ( $result );
?>
url是一个java rest api服务。在服务端收到此GET请求时,显示所有标头值为null。 我用邮递员测试了服务,并设置了标题,然后通过。 不确定我在PHP代码中缺少什么。
我服务的代码段:
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) req;
String token = httpRequest.getHeader("Authorization");
String userEmail = httpRequest.getHeader("ulogin");
}
更新
我用postman和一个示例java客户端测试过。两者都有效。只有从php才能正常工作。
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:8080/api/order/165");
request.addHeader("Content-Type", "application/json");
request.addHeader("ulogin", "abc"); r
request.addHeader("Authorization", "abcdefg");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
System.out.println( response.getHeaders("Authorization"));
}
UPDATE2
使用get_file_contents也可以
$url = "http://localhost:8080/api/order/165";
$options = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content-Type: application/json\r\n" .
"ulogin: abc\r\n" .
"Authorization:abcdefg\r\n"
)
);
$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);
var_dump($file);
答案 0 :(得分:0)
答案 1 :(得分:0)
如何在php中设置标头没有任何问题。
当你调用一个显示请求标题的php脚本时,它会显示你设置的3个标题。将以下代码粘贴到新的php文件中,并使用当前代码调用它。你会发现它很棒。
var_dump(getallheaders());
curl_close中的一个小注释,你需要添加curl处理程序而不是你解析的结果。更改以下行
curl_close ( $result );
要
curl_close( $curl );