HTTP状态405 - 请求方法' POST'使用POSTMAN Client运行API时不支持

时间:2015-09-11 11:08:22

标签: web-services rest spring-mvc spring-security postman

我在postman客户端的帮助下执行一个rest API,作为测试我的Spring MVC应用程序的一部分。

在测试GET API时,我得到了正确的响应,但是当我通过POSTMAN客户端发出POST请求时,我收到405错误

以下是我的档案:

WebController

    package com.websystique.springsecurity.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;





import com.websystique.springsecurity.model.Operations;
import com.websystique.springsecurity.service.KeywordService;
import com.websystique.springsecurity.service.OperationService;

@RestController
public class WebserviceController {

    @Autowired
    KeywordService keywordService;

    @Autowired
    OperationService operationService;


    @RequestMapping(value = "/webservice/keywords", method = RequestMethod.GET)
    public ResponseEntity<List<String>> listAllKeywords() {
        List<String> keywords = keywordService.listAllKeywords();
        if(keywords.isEmpty()){
            return new ResponseEntity<List<String>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<String>>(keywords, HttpStatus.OK);
    }

    @RequestMapping(value = "/webservice/findalloperations",method = RequestMethod.GET)
    public ResponseEntity<List<Operations>> findAllOperations() {
        List<Operations> operations =  operationService.findAllOperations();
        if(operations.isEmpty()) {
            return new ResponseEntity<List<Operations>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<Operations>>(operations, HttpStatus.OK);
    }

    @RequestMapping(value ="/webservice/getOperation" , method = RequestMethod.POST)
    public ResponseEntity<Operations> findOperationByKeyword(@RequestBody String keyword) {

        System.out.println("Running webservice for keyword" + keyword);
        Operations operation = operationService.findOperationByKeyword(keyword);
        if(operation == null) {
            return new ResponseEntity<Operations>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<Operations>(operation,HttpStatus.OK);

    }

    @RequestMapping(value ="/webservice/getOperation/{keyword}" , method = RequestMethod.GET)
    public ResponseEntity<Operations> findOperationByKeywordGet(@PathVariable String keyword) {

        System.out.println("Running webservice for keyword" + keyword);
        Operations operation = operationService.findOperationByKeyword(keyword);
        if(operation == null) {
            return new ResponseEntity<Operations>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<Operations>(operation,HttpStatus.OK);

    }

    @RequestMapping(value ="/webservice/getAllOperationNames" , method = RequestMethod.GET)
    public ResponseEntity<List<String>> findAllOperationName() {

        System.out.println("Getting all operation names");
        List<String> operationnames = operationService.findAllOperationName();
        if(operationnames.isEmpty()) {
            return new ResponseEntity<List<String>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<String>>(operationnames,HttpStatus.OK);

    }


}

SecurityWebApplicationInitializer

package com.websystique.springsecurity.configuration;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}

SecurityConfiguration:

package com.websystique.springsecurity.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
        auth.inMemoryAuthentication().withUser("Ashvarya").password("ashvarya123").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()
      //----------------------------------------------------------
        .antMatchers("/index").permitAll()
        .antMatchers("/webservice/**").permitAll()
        //-------------------------------------------------------
        .antMatchers("/", "/home").access("hasRole('USER') or hasRole('ADMIN')")
        .antMatchers("/protected/**").access("hasRole('USER') or hasRole('ADMIN')")
        .antMatchers("/admin/**").access("hasRole('ADMIN')")
        .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
        .and().formLogin()
        .and().formLogin().loginPage("/login")
        .usernameParameter("ssoId").passwordParameter("password")
        .and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");

    }
}

CORSFilter:

package com.websystique.springsecurity.configuration;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        System.out.println("Filtering on...........................................................");
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

POST网址:http://localhost:8080/AutomationToolWebPortal/webservice/getOperation

POST请求:

    {

    "keyword":"Click"
}

响应标题已收到:

Access-Control-Allow-Headers → x-requested-with, Content-Type
Access-Control-Allow-Methods → POST, GET, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin → *
Access-Control-Max-Age → 3600
Allow → GET
Cache-Control → no-cache, no-store, max-age=0, must-revalidate
Content-Language → en
Content-Length → 1090
Content-Type → text/html;charset=ISO-8859-1
Date → Fri, 11 Sep 2015 10:36:06 GMT
Expires → 0
Pragma → no-cache
Server → Apache-Coyote/1.1
X-Content-Type-Options → nosniff
X-Frame-Options → DENY
X-XSS-Protection → 1; mode=block

我已经针对这个问题找到了不同的答案,但大多数人都在谈论在请求中发送csrfilter。不知道如何在邮递员那样做。 请帮忙

0 个答案:

没有答案