相关疑难解决方法(0)

我可以覆盖使用java的HttpUrlConnection类的Host头吗?

我正在使用以下代码在java中打开http连接:

 URL url = new URL("http://stackoverflow.com");
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 conn.setDoOutput(true);
 conn.setRequestMethod("GET");
 conn.setRequestProperty("Host", "Test:8080");
 conn.getOutputStream();
Run Code Online (Sandbox Code Playgroud)

但是,调用conn.setRequestProperty("Host","Test:8080")似乎无效,无论我调用方法的顺序如何,主机都重置为目标服务器.有没有办法在不使用其他库的情况下覆盖Host头?

TIA Matt

java networking http urlconnection httpurlconnection

23
推荐指数
2
解决办法
2万
查看次数

为 Spring RestTemplate 设置“Host”标头不起作用

我想通过交换方法使用Spring RestTemplate发送 HTTP 请求。

第三个参数是 的一个实例HttpEntity,它允许设置请求的标头/正文。我尝试了以下代码片段:

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public class Connector {
    public static void main(String[] args) {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Host", "www.example.com");
        headers.set("User-Agent", "whatever");


        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                "http://httpbin.org/headers", HttpMethod.GET,
                new HttpEntity<String>(null, headers), String.class);

        System.out.println(responseEntity.getBody());
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,http : //httpbin.org/headers是一个简单的 HTTP 请求和响应服务,它(在本例中)返回 HTTP 标头。

运行Java代码的结果如下:

{
  "headers": {
    "Accept": "text/plain, */*", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "whatever"
  }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,User-Agent设置为我想要的,但 …

java rest spring resttemplate

6
推荐指数
1
解决办法
1万
查看次数