简体   繁体   中英

404 Error when sending HTTP request through java

I seem to be getting a 404 error when sending a http post to a sinatra server. I am trying to make the server page the text I send to it, here's my code I think it may be something wrong with my server but I'm not sure:

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());

}

and here is the sinatra server (ruby):

require 'sinatra'


get '/' do
'hello mate'
end

get '/boo' do
'trololo'
end

Could your problem be realated to trying to use a HTTPS (instead of HTTP) connections? I am looing at the use of HttpsURLConnection .

Since you're sending your HTTP request via POST, shouldn't your sinatra server routes bet post instead of get ? Would explain why you're getting a 404. Something like this should sort it out:

require 'sinatra'

post '/' do
  'hello mate'
end

post '/boo' do
  'trololo'
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM