0

将 http 帖子发送到 sinatra 服务器时,我似乎遇到了 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 服务器(红宝石):

require 'sinatra'


get '/' do
'hello mate'
end

get '/boo' do
'trololo'
end
4

2 回答 2

0

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

于 2013-08-23T17:01:09.807 回答
0

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

require 'sinatra'

post '/' do
  'hello mate'
end

post '/boo' do
  'trololo'
end
于 2013-08-24T11:25:27.340 回答