简体   繁体   中英

How to set 'Referer' HTTP header using Apache HttpComponents HttpClient

I wrote php curl to request some data from my API server, and now I want to develop a JSP to request the data from the same API server.

The problem comes when my API server need http referer to check if the request come from a valid url.

My original PHP is:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/2');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
$html = curl_exec($ch);

... then my api server get the referer url with

var_dump($_SERVER['HTTP_REFERER'])

How do I use Apache HttpComponents HttpClient to set the Referer header?

HttpGet request = new HttpGet("http://www.example.com/2")

request.addHeader("Referer", "http://www.example.com/1")

HttpResponse response = HttpClientBuilder.create().build().execute(request)

You can set header by using AbstractHttpMessage addHeader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM