【问题标题】:404 Error when sending HTTP request through java通过java发送HTTP请求时出现404错误
【发布时间】:2013-08-25 17:06:59
【问题描述】:

在向 sinatra 服务器发送 http 帖子时,我似乎遇到了 404 错误。我正在尝试使服务器页面成为我发送给它的文本,这是我的代码,我认为我的服务器可能有问题,但我不确定:

private void sendInfo() throws Exception {
    //make the string and URL
    String url = "http://localhost";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    //send post
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'post' request to url: " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response code: " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

这里是 sinatra 服务器(ruby):

require 'sinatra'


get '/' do
'hello mate'
end

get '/boo' do
'trololo'
end

【问题讨论】:

  • 您是否在端口 80 上运行 Sinatra 应用程序?因为默认情况下 Sinatra 在端口 4567 上运行。
  • @tadejm 抱歉,这是一个错字,仍然出现此错误:向 url 发送“发布”请求:127.0.0.1:4567 发布参数:/boo 响应代码:线程“main”java.io 中的 404 异常。 FileNotFoundException:127.0.0.1:4567
  • 在 Sinatra 应用服务器日志中,你看到发送的请求了吗?
  • @Tadejm 是的,但它说的是“错误连接强制关闭”
  • 据我所知,这个错误暗示你正在尝试通过 tcp/ip 连接到 sql 数据库:technet.microsoft.com/en-us/library/…

标签: java ruby http sinatra http-status-code-404


【解决方案1】:

您的问题是否与尝试使用 HTTPS(而不是 HTTP)连接有关?我正在寻找HttpsURLConnection 的使用。

【讨论】:

    【解决方案2】:

    既然您是通过 POST 发送 HTTP 请求,那么您的 sinatra 服务器路由不应该赌 post 而不是 get 吗?会解释为什么你会得到一个 404。这样的事情应该解决它:

    require 'sinatra'
    
    post '/' do
      'hello mate'
    end
    
    post '/boo' do
      'trololo'
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2022-08-03
      • 2018-05-27
      • 2021-11-15
      相关资源
      最近更新 更多