首页 > 解决方案 > 为什么 Http Post 在发送到 ip 时有效,但在发送到 url 时无效?

问题描述

我正在使用org.apache.http.client.methods.HttpPost从我的服务器获取一行信息。

当我使用服务器的 IP 地址时(以下仅为示例),我得到了预期的信息:

HttpPost("http://127.0.0.1/api/fetchInfo")

但是,当我使用 URL 时,服务器没有收到请求,客户端收到运行时错误:org.apache.http.client.HttpResponseException: Not Found。

HttpPost("http://subdomain.domain.com/api/fetchInfo")

URL 包含一个子域。

我试图访问的服务器是网站提供商,我能够通过域与网站进行交互,因此域存在。

客户端在我的本地计算机上,服务器在亚马逊 ec2 上。

如何使其与网址一起使用?

我的代码:

    String responseString = "";
    try {

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setCharset(Charset.forName("UTF-8")).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        HttpEntity entity = multipartEntityBuilder.build();
        HttpPost request = new HttpPost("http://subdomain.domain.com/api/fetchInfo");

        request.setEntity(entity);

        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(request);

        responseString = new BasicResponseHandler().handleResponse(response);
    } catch (IOException ex) {
        log(ex)
    }
    return responseString;

标签: java

解决方案


如果您使用的是 apache 服务器,那么您需要使用服务器名称 subdomain.domain.com 配置 subdomain.conf 文件,并在机器上的 /etc/hosts 文件中指定 subdomain.domain.com 名称的映射使用 ip 127.0.0.1。

我希望这有帮助。


推荐阅读