简体   繁体   中英

Java http call returning response code: 501

I am having an issue with this error:

**Server returned HTTP response code: 501 for URL: http://dev1:8080/data/xml/01423_01.xml**      

See this code:

   private static Map sendRequest(String hostName, String serviceName) throws Exception {
         Map assets = null;
         HttpURLConnection connection = null;

         Authenticator.setDefault(new Authenticator());


         URL serviceURL = new URL(hostName + "/" + serviceName);
         connection = (HttpURLConnection)serviceURL.openConnection();
         connection.setRequestMethod("GET");
         ClientHttpRequest postRequest = new ClientHttpRequest(connection);

         InputStream input = null;


         /*

         At line input = postRequest.post(); I get the following error
         Server returned HTTP response code: 501 for URL: http://dev1:8080/data/xml/01423_01.xml

         Yet if I enter that url in my browser it opens up fine.  
         Is this a common problem? Is there some type of content type I need to set?
         */
         input = postRequest.post();
         connection.disconnect();
         return assets;
     }

A 501 response means "not implemented", and is usually taken to mean that the server didn't understand the HTTP method that you used (eg get, post, etc).

I don't recognise ClientHttpRequest , but you have a line that says

connection.setRequestMethod("GET");

and then a line that says

input = postRequest.post();

I'm not sure what post() actually does, but does that mean send a POST request? If so, then that contradicts the GET specified in the first line.

Either way, the server is saying that it doesn't under the GET or the POST method, whichever one your code is actually sending. You need to find out what method the server does support for that URL, and use that.

Perhaps you should check your port settings:

 new URL(hostName + "/" + serviceName);

Looks like the port number ":8080" is missing.

Some server expect additional information from the client in the request like a user agent or some form data. Even cookies could be expected by the application running on the server. You should also check the complete response and not only the response code.

I would recommend you to use a library like httpclient that is more convenient: https://hc.apache.org/httpcomponents-client-ga/index.html

Here is simple usage example:
https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientWithResponseHandler.java

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