我正在用弹簧靴做休息api.我需要使用输入参数(使用方法,例如GET,POST等),请求路径,查询字符串,此请求的相应类方法,以及此操作的响应,成功和错误来记录所有请求.
举个例子:
成功要求:
http://example.com/api/users/1
Run Code Online (Sandbox Code Playgroud)
日志应该看起来像这样:
{
HttpStatus: 200,
path: "api/users/1",
method: "GET",
clientIp: "0.0.0.0",
accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
method: "UsersController.getUser",
arguments: {
id: 1
},
response: {
user: {
id: 1,
username: "user123",
email: "user123@example.com"
}
},
exceptions: []
}
Run Code Online (Sandbox Code Playgroud)
或者请求错误:
http://example.com/api/users/9999
Run Code Online (Sandbox Code Playgroud)
日志应该是这样的:
{
HttpStatus: 404,
errorCode: 101,
path: "api/users/9999",
method: "GET",
clientIp: "0.0.0.0",
accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
method: "UsersController.getUser",
arguments: {
id: 9999
},
returns: {
},
exceptions: [
{
exception: "UserNotFoundException",
message: "User with id 9999 not found",
exceptionId: "adhaskldjaso98d7324kjh989",
stacktrace: ................... …Run Code Online (Sandbox Code Playgroud) 我试图在基于Spring的REST API中读取HTTP头.我跟着这个.但是我收到了这个错误:
没有找到类java.lang.String,
ContentType:application/octet-stream的消息正文阅读器
我是Java和Spring的新手,所以无法解决这个问题.
这就是我的通话方式:
@WebService(serviceName = "common")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public interface CommonApiService {
@GET
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
@Path("/data")
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @DefaultValue ("") @QueryParam("ID") String id);
}
Run Code Online (Sandbox Code Playgroud)
我试过了@Context:HTTPHeader是null这种情况.
如何从HTTP标头获取值?
Abstract控制器类需要REST中的对象列表.使用Spring RestTemplate时,它不会将其映射到所需的类,而是返回Linked HashMAp
public List<T> restFindAll() {
RestTemplate restTemplate = RestClient.build().restTemplate();
ParameterizedTypeReference<List<T>> parameterizedTypeReference = new ParameterizedTypeReference<List<T>>(){};
String uri= BASE_URI +"/"+ getPath();
ResponseEntity<List<T>> exchange = restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
List<T> entities = exchange.getBody();
// here entities are List<LinkedHashMap>
return entities;
}
Run Code Online (Sandbox Code Playgroud)
如果我用,
ParameterizedTypeReference<List<AttributeInfo>> parameterizedTypeReference =
new ParameterizedTypeReference<List<AttributeInfo>>(){};
ResponseEntity<List<AttributeInfo>> exchange =
restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
Run Code Online (Sandbox Code Playgroud)
它工作正常.但不能放入所有子类,任何其他解决方案.
如何从spring rest模板中获取原始json字符串?我试过跟随代码,但它返回我没有引号的json导致其他问题,我怎么能得到json原样.
ResponseEntity<Object> response = restTemplate.getForEntity(url, Object.class);
String json = response.getBody().toString();
Run Code Online (Sandbox Code Playgroud) 我有一些没有web.xml的Spring RESTful(RestControllers)Web服务,我使用Spring启动来启动服务.
我想为Web服务添加授权层,并希望在实际调用Web服务本身之前将所有http请求路由到一个前端控制器.(我有一个代码来模拟autherisation层的会话行为,根据我从客户端发送的每个httpRequest生成的密钥来验证用户).
是否有任何标准Spring解决方案将所有请求路由到过滤器/前端控制器?
提前谢谢,Praneeth
编辑:添加我的代码
控制器:`
@RestController
public class UserService {
UserDAO userDAO = new UserDAO();
@RequestMapping(value="/login", method = RequestMethod.POST)
@LoginRequired
public String login(@RequestParam(value="user_name") String userName, @RequestParam(value="password") String password, HttpServletRequest request){
return userDAO.login(userName, password);
}
}`
Run Code Online (Sandbox Code Playgroud)
拦截器:
`
public class AuthenticationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("In Interceptor");
//return super.preHandle(request, response, handler);
return true;
}
@Override
public void postHandle( HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception …Run Code Online (Sandbox Code Playgroud) 我有一个拥有不同消费者的api.我希望他们根据他们在春季安全中的角色获取相关文档.
例如
Api操作A受限于角色A和角色B.
Api操作B受限于角色B.
Api操作C对所有人开放
我正在使用springfox,spring 4,spring rest,security
我知道有一个名为@ApiIgnore的注释,也许可以使用它.
这是可能吗?
根据Current SpringBoot参考指南,如果我设置spring.jackson.date-format属性,它将:Date format string or a fully-qualified date format class name. For instance 'yyyy-MM-dd HH:mm:ss'.
但是,Spring Boot 1.5.3无法以这种方式工作.
为了演示,从这个类开始:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
class NowController{
@GetMapping("/now")
Instant getNow(){
return Instant.now();
}
}
Run Code Online (Sandbox Code Playgroud)
还有这个 src/main/resources/application.properties
spring.jackson.date-format=dd.MM.yyyy
Run Code Online (Sandbox Code Playgroud)
这个build.gradle:
buildscript {
ext {
springBootVersion = '1.5.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies { …Run Code Online (Sandbox Code Playgroud) spring jackson spring-boot spring-restcontroller spring-rest
寻找有关正确处理验证错误的Spring数据休息验证的一些帮助:
我对这里关于spring-data-rest验证的文档非常困惑:http://docs.spring.io/spring-data/rest/docs/current/reference/html/#validation
我正在尝试正确处理试图保存新公司实体的POST调用的验证
我有这个实体:
@Entity
public class Company implements Serializable {
@Id
@GeneratedValue
private Long id;
@NotNull
private String name;
private String address;
private String city;
private String country;
private String email;
private String phoneNumber;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "company")
private Set<Owner> owners = new HashSet<>();
public Company() {
super();
}
Run Code Online (Sandbox Code Playgroud)
...
和这个RestResource dao
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RestResource;
import com.domain.Company;
@RestResource
public interface CompanyDao extends PagingAndSortingRepository<Company, Long> {
}
Run Code Online (Sandbox Code Playgroud)
POST请求api /公司:
{
"address" : "One Microsoft …Run Code Online (Sandbox Code Playgroud) 我正在编写一个Rest客户端来使用Spring RestTemplate发布JSON数据.在正文中使用POSTMAN和跟随JSON数据获得正确的响应 -
{
"InCode":"test",
"Name":"This is test",
"Email":"test@gmail.com",
"Id":18,
}
Run Code Online (Sandbox Code Playgroud)
但是,当尝试使用Spring RestTemplate按如下方式命中REST API时
ResponseEntity<String> response = restTemplate.exchange(baseUrl,
HttpMethod.POST, getHeaders(), String.class);
private HttpEntity<?> getHeaders() throws JSONException {
JSONObject request = new JSONObject();
request.put("Email", "test@gmail.com");
request.put("Id", "18");
request.put("Name", "This is test");
request.put("InCode", "test");
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
return new HttpEntity<>(request.toString(), headers);
}
Run Code Online (Sandbox Code Playgroud)
我得到例外 -
11:52:56.808 [main] DEBUG o.s.web.client.RestTemplate - Created POST request for "http://server-test/platform/v4/org"
11:52:56.815 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
12:03:47.357 [main] DEBUG o.s.web.client.RestTemplate - …Run Code Online (Sandbox Code Playgroud) 我对我的RestController进行了简单的测试.我希望$[1].parent_id返回Long作为对象而不是整数原语.如果parent_id在长数字范围和>整数范围内(例如:2147483650L),它将返回Long .
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@WebAppConfiguration
public class TransactionServiceControllerTest {
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
// I copy this from my RestController class
this.transactions = Arrays.asList(
new Transaction(100d, "car", null),
new Transaction(100d, "table", 12L)
);
}
@Test
public void readSingleBookmark() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/transaction/"))
.andExpect(content().contentType(contentType)) // ok
.andExpect(jsonPath("$", hasSize(2))) // ok
//omitted
andExpect(jsonPath("$[1].parent_id",is(this.transactions.get(1).getParentId())));
} //assertion fail
Expected: is <12L>
but: was <12>
Run Code Online (Sandbox Code Playgroud)
另一项测试的结果:
Expected: is <12L>
but: was <2147483650L> …Run Code Online (Sandbox Code Playgroud) spring-rest ×10
java ×6
spring ×5
jackson ×2
json ×2
rest ×2
resttemplate ×2
spring-boot ×2
spring-mvc ×2
logging ×1
spring-test ×1
spring-web ×1
springfox ×1
swagger ×1