Ошибка 405 java

Am asking this question after doing some research. I did followed the solutions given for this kind of error but did not work for me. Any suggestions as where am going wrong in the below code.I am creating a REST API but when I request the url it is giving me the 405 error.Below is the URI am requesting.

    http://localhost:8080/Project/services/start/version

Below is the code snippet.

@Path("/start")

public class StartService {
@GET
@Path("/version")
@Produces({"text/plain","application/xml","application/json"})
public String getVersion() {
    String ver="";

    try{


          Runtime rt = Runtime.getRuntime();
          Process pr = rt.exec("C:\server\dgr -v" );

          BufferedReader stdInput = new BufferedReader(new InputStreamReader
(pr.getInputStream()));
          BufferedReader input = new BufferedReader(stdInput);
         // String ver ="";
          StringBuffer verOutput = new StringBuffer();
                while((ver =  input.readLine()) != null){
                    verOutput.append(ver + "n");
                    System.out.println(ver);
                }


        }catch (Throwable t)  
          {  
            t.printStackTrace();  
          }  


        finally {  

        }
    return ver;  }

}

web.xml:

<web-app 
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

<servlet>
<display-name>eLicensingWeb</display-name>      
    <servlet-name>JAX-RS REST</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <init-param>
         <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.cem.plc.service</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
</servlet>




<servlet-mapping>
    <servlet-name>JAX-RS REST</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>


<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>


</web-app>

asked Oct 2, 2013 at 18:20

user2821894's user avatar

8

You might be doing a PUT call for GET operation
Please check once

answered Aug 27, 2020 at 17:59

Vivek Mishra's user avatar

1

In above code variable «ver» is assign to null, print «ver» before returning and see the value. As this «ver» having null service is send status as «204 No Content».

And about status code «405 — Method Not Allowed» will get this status code when rest controller or service only supporting GET method but from client side your trying with POST with valid uri request, during such scenario get status as «405 — Method Not Allowed»

answered Jun 27, 2019 at 4:58

Girish's user avatar

GirishGirish

1073 silver badges10 bronze badges

@Produces({"text/plain","application/xml","application/json"})

change this to

@Produces("text/plain")

and try,

shA.t's user avatar

shA.t

16.5k5 gold badges54 silver badges111 bronze badges

answered Dec 24, 2013 at 13:13

user2721787's user avatar

3

I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure

So check for your server how it works and enable CORS. I didn’t even need a browser plugin or proxy :)

answered Jan 21, 2017 at 20:29

seawave_23's user avatar

seawave_23seawave_23

1,1492 gold badges12 silver badges22 bronze badges

Add

@Produces({"image/jpeg,image/png"})

to

@POST
@Path("/pdf")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({"image/jpeg,image/png"})
//@Produces("text/plain")
public Response uploadPdfFile(@FormDataParam("file") InputStream fileInputStream,@FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception {
    ...
}

bluish's user avatar

bluish

26k27 gold badges120 silver badges179 bronze badges

answered Sep 1, 2016 at 15:48

Gene's user avatar

GeneGene

10.8k1 gold badge66 silver badges58 bronze badges

I had the same issue. In my case the Url had portions of it missing
For example :

http://localhost:8080/root/path/action

Instead I had something like

http://localhost:8080/root/action

Take away is check if the URL is correct. In my case I corrected my URL and the issue was resolved.

Seemant Shukla's user avatar

answered Jun 2, 2022 at 6:47

Gayathri's user avatar

GayathriGayathri

651 silver badge11 bronze badges

When I got 405 when making a rest call, I did all research and none worked for me. Finally I realized I did not put the right version of code in tomcat. Once the code with the method is in place, the rest call worked. Just want to put here FYI.
Please check your version of code first!!!!

answered May 26, 2022 at 18:49

Janet's user avatar

JanetJanet

7429 silver badges13 bronze badges

I am new to the rest services. I am trying to create a service that accepts json string from a client. I am getting 405 error when I am calling this service using JQuery. Below is the Java code for ws:

This is the way i am posting a request to JERSEY POST RESTFUL Webservice .

var orderinfo = {'ordersplitjson': ordersplitjson, 'customer_id': cust_id , 'homedelivery': homedelivery, 'seatnum' :seatnum , 'locationname':location_nam , 'rownum':rownum}; 
var json_data =  JSON.stringify(orderinfo);
        var ajaxcallquery = $.ajax({
            type:'POST',
              dataType: 'jsonp',
             data: json_data,
             contentType: "application/json; charset=utf-8",
            url:url+'/OMS/oms1/orderinsertservice',
            jsonpCallback:'jsonCallback',
            jsonp:false,
            success: function(response) 
            {
            },
            error: function(jqxhr, status, errorMsg) {
            alert('Failed! ' + errorMsg);
        }

        });


 public class OrdersInsertService 
{
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces("application/json")
    public String getData(OrderInfo order,@Context HttpServletResponse serverResponse)
    throws JSONException
            {
         serverResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
            serverResponse.addHeader("Access-Control-Allow-Credentials", "true");
            serverResponse.addHeader("Access-Control-Allow-Origin", "*");
           serverResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
            serverResponse.addHeader("Access-Control-Max-Age", "60");

}
}


package com.util;

public class OrderInfo {

    String ordersplitjson;
    public String getOrdersplitjson() {
        return ordersplitjson;
    }
    public void setOrdersplitjson(String ordersplitjson) {
        this.ordersplitjson = ordersplitjson;
    }
    public String getCustomer_id() {
        return customer_id;
    }
    public void setCustomer_id(String customer_id) {
        this.customer_id = customer_id;
    }
    public String getHomedelivery() {
        return homedelivery;
    }
    public void setHomedelivery(String homedelivery) {
        this.homedelivery = homedelivery;
    }
    public String getSeatnum() {
        return seatnum;
    }
    public void setSeatnum(String seatnum) {
        this.seatnum = seatnum;
    }
    public String getLocationname() {
        return locationname;
    }
    public void setLocationname(String locationname) {
        this.locationname = locationname;
    }
    public String getRownum() {
        return rownum;
    }
    public void setRownum(String rownum) {
        this.rownum = rownum;
    }
    String customer_id;

    String homedelivery;
    String seatnum;

    String locationname;
    String rownum;


}

Could anybody please let me know how to fix this

enter image description here

I am using Jersey 1 ,When i used your class its giving me a compiltion error in eclipse as hwon in picture

enter image description here

Автор оригинала: baeldung.

1. Обзор

Эта краткая статья посвящена распространенной ошибке – “Метод запроса не поддерживается – 405”, с которой сталкиваются разработчики, предоставляя свои API для определенных HTTP – глаголов с помощью Spring MVC.

Естественно, мы также обсудим общие причины этой ошибки.

2. Основы метода запроса

Прежде чем перейти к общей проблеме, если вы только начинаете изучать Spring MVC, вот хорошая вступительная статья для начала.

Давайте также очень быстро рассмотрим основы – и поймем методы запроса, поддерживаемые Spring, и некоторые из общих классов, представляющих здесь интерес.

В очень упрощенном виде методы HTTP MVC-это основные операции, которые запрос может инициировать на сервере. Например, некоторые методы извлекают данные с сервера, некоторые отправляют данные на сервер, некоторые могут удалять данные и т. Д.

@RequestMapping аннотация указывает поддерживаемые методы для запроса.

Spring объявляет все поддерживаемые методы запроса под перечислением RequestMethod ; он указывает стандартные GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE глаголы.

Spring DispatcherServlet поддерживает все из них по умолчанию, за исключением OPTIONS и TRACE ; @RequestMapping использует перечисление RequestMethod , чтобы указать, какие методы поддерживаются.

3. Простой сценарий MVC

Теперь давайте рассмотрим пример кода, который сопоставляет все методы HTTP:

@RestController
@RequestMapping(value="/api")
public class RequestMethodController {

    @Autowired
    private EmployeeService service;

    @RequestMapping(value = "/employees", produces = "application/json")
    public List findEmployees()
      throws InvalidRequestException {
        return service.getEmployeeList();
    }
}

Обратите внимание, как в примере объявляется метод findEmployee () . Он не указывает какой-либо конкретный метод запроса, что означает, что этот URL-адрес поддерживает все методы по умолчанию.

Мы можем запросить API, используя различные поддерживаемые методы, например, с помощью curl:

$ curl --request POST http://localhost:8080/api/employees
[{"id":100,"name":"Steve Martin","contactNumber":"333-777-999"},
{"id":200,"name":"Adam Schawn","contactNumber":"444-111-777"}]

Естественно, мы можем отправить запрос несколькими способами – с помощью простой команды curl , Postman, AJAX и т. Д.

И, конечно же, мы ожидаем получить ответ 200 OK , если запрос правильно отображен и успешен.

4. Сценарий проблемы – HTTP 405

Но то, что мы здесь обсуждаем, – это, конечно, сценарии, когда запрос не будет успешным.

405 Метод Не разрешен ” – одна из наиболее распространенных ошибок, которые мы наблюдаем при работе с запросами Spring.

Давайте посмотрим, что произойдет, если мы специально определим и обработаем запросы GET в Spring MVC, как это:

@RequestMapping(
  value = "/employees", 
  produces = "application/json", 
  method = RequestMethod.GET)
public List findEmployees() {
    ...
}

// send the PUT request using CURL
$ curl --request PUT http://localhost:8080/api/employees
{"timestamp":1539720588712,"status":405,"error":"Method Not Allowed",
"exception":"org.springframework.web.HttpRequestMethodNotSupportedException",
"message":"Request method 'PUT' not supported","path":"/api/employees"}

В этом предыдущем сценарии мы получаем HTTP – ответ с кодом состояния 405 – ошибка клиента, указывающая на то, что сервер не поддерживает метод/глагол, отправленный в запросе.

Как следует из названия, причиной этой ошибки является отправка запроса с помощью неподдерживаемого метода.

Как вы можете ожидать, мы можем решить эту проблему, определив явное сопоставление для PUT в существующем сопоставлении методов:

@RequestMapping(
  value = "/employees", 
  produces = "application/json", 
  method = {RequestMethod.GET, RequestMethod.PUT}) ...

В качестве альтернативы мы можем определить новый метод/отображение отдельно:

@RequestMapping(value = "/employees", 
  produces = "application/json", 
  method=RequestMethod.PUT)
public List postEmployees() ...

6. Заключение

Метод/глагол запроса является критическим аспектом в HTTP-коммуникации, и мы должны быть осторожны с точной семантикой операций, которые мы определяем на стороне сервера, а затем с точными запросами, которые мы отправляем.

И, как всегда, примеры, показанные в этой статье, доступны на на GitHub .

1. Overview

This quick article is focused on a common error – ‘Request Method not Supported – 405′ – that developers face while exposing their APIs for specific HTTP verbs, with Spring MVC.

Naturally, we’ll also discuss the common causes of this error.

2. Request Method Basics

Before moving towards the common problem, if you’re just starting to learn about Spring MVC, here’s a good intro article to start with.

Let’s also have a very quick look at the basics – and understand the request methods supported by Spring and some of the common classes of interest here.

In a highly simplified way, MVC HTTP methods are basic operations that a request can trigger on the server. For example, some methods fetch the data from the server, some submit data to the server, some might delete the data etc.

The @RequestMapping annotation specifies the supported methods for the request.

Spring declares all the supported request methods under an enum RequestMethod; it specifies the standard GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE verbs.

The Spring DispatcherServlet supports all of them by default except OPTIONS and TRACE@RequestMapping uses the RequestMethod enum to specifies which methods are supported.

3. Simple MVC Scenario

Now, let’s have a look at a code example that maps all HTTP methods:

@RestController
@RequestMapping(value="/api")
public class RequestMethodController {

    @Autowired
    private EmployeeService service;

    @RequestMapping(value = "/employees", produces = "application/json")
    public List<Employee> findEmployees()
      throws InvalidRequestException {
        return service.getEmployeeList();
    }
}

Notice how the example declares findEmployee() method. It doesn’t specify any specific request method, which means this URL supports all default methods.

We can request the API using different supported methods, for example, using curl:

$ curl --request POST http://localhost:8080/api/employees
[{"id":100,"name":"Steve Martin","contactNumber":"333-777-999"},
{"id":200,"name":"Adam Schawn","contactNumber":"444-111-777"}]

Naturally, we can send the request in multiple ways – via a simple curl command, Postman, AJAX, etc.

And, of course, we’re expecting to get the 200 OK response, if the request is correctly mapped and successful.

4. Problem Scenario – the HTTP 405

But, what we’re discussing here is – of course – the scenarios when the request won’t be successful.

405 Method Not Allowed’ is one of the most common errors we observe while working with Spring requests.

Let’s have a look at what happens if we specifically define and handle GET requests in Spring MVC, like this:

@RequestMapping(
  value = "/employees",
  produces = "application/json",
  method = RequestMethod.GET)
public List<Employee> findEmployees() {
    ...
}

// send the PUT request using CURL
$ curl --request PUT http://localhost:8080/api/employees
{"timestamp":1539720588712,"status":405,"error":"Method Not Allowed",
"exception":"org.springframework.web.HttpRequestMethodNotSupportedException",
"message":"Request method 'PUT' not supported","path":"/api/employees"}

[[Not Support – Reason, Solution

[[What we’re getting in this previous scenario is the HTTP response with the 405 Status Code – a client error that indicates that the server doesn’t support the method/verb sent in the request.

As the name suggests here, the reason for this error is sending the request with a non-supported method.

As you can expect, we can solve this by defining an explicit mapping for PUT, in the existing method mapping:

@RequestMapping(
  value = "/employees",
  produces = "application/json",
  method = {RequestMethod.GET, RequestMethod.PUT}) ...

Alternatively, we can define the new method/mapping separately:

@RequestMapping(value = "/employees",
  produces = "application/json",
  method=RequestMethod.PUT)
public List<Employee> postEmployees() ...

6. Conclusion

The request method/verb is a critical aspect in HTTP communication, and we need to be careful with the exact semantics of the operations we define on the server side, and then with the exact requests we’re sending in.

And as always, the examples shown in this article are available on over on GitHub.

I am getting the error HTTP Status 405 - HTTP method POST is not supported by this URL when I use the following code(below) … the line causing the trouble (apparently) is getServletContext().getRequestDispatcher("/EditObject?id="+objId).forward(request, response);

package web.objects;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.ObjDetailsDao;

@SuppressWarnings("serial")
public class EditObjectText extends HttpServlet {

 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


  int objId = Integer.parseInt(request.getParameter("objId"));
  String text = (String)request.getParameter("description");

  ObjDetailsDao oddao = new ObjDetailsDao();
   try {
oddao.modifyText(text, objId);
 /////////////
    getServletContext().getRequestDispatcher("/EditObject?id="+objId).forward(request, response);
 ////////////
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (ServletException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
        }
      }
}

EDIT: I added the throws ServletException, IOException as suggested, but this did not change the error.

EDIT: the EditObject servlet looks like this

 @SuppressWarnings("serial")
public class EditObject extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        int objId = Integer.parseInt(request.getParameter("id"));
        dispPage(objId, request, response);
    }

    private void dispPage(int objId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{        

// ... lots of code in here
            getServletContext().getRequestDispatcher("/jsp/objectPageEdit.jsp").forward(request, response);

    }
}

ANOTHER EDIT: So basically I can’t do what I am doing. What I need is this, the user submits a post request and then I refer him/her back to a servlet which uses the Get method instead of Post. How can I do this referral without getting the error? Thanks in advance.

Понравилась статья? Поделить с друзьями:
  • Ошибка 405 http что это
  • Ошибка 405 flask
  • Ошибка 405 api
  • Ошибка 404b что это
  • Ошибка 4049 мерседес атего