404通过java发送HTTP请求时出错

时间:2013-08-22 19:39:05

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

在向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

2 个答案:

答案 0 :(得分:0)

您的问题可能与尝试使用HTTPS(而不是HTTP)连接有关吗?我正在考虑使用HttpsURLConnection

答案 1 :(得分:0)

由于您是通过POST发送HTTP请求,因此您的sinatra服务器不应该路由post而不是get?可以解释为什么你得到404.这样的东西应该解决它:

require 'sinatra'

post '/' do
  'hello mate'
end

post '/boo' do
  'trololo'
end