2016-01-06 33 views
0

我正在嘗試編寫spring REST代碼來獲取由android用戶發送的參數。例如android用戶填寫表單並點擊發送按鈕。現在我想要在REST API中接收值或參數。我搜索谷歌,但無法弄清楚如何做到這一點。下面是我試過的代碼,但沒有奏效GET請求從春天的REST API接收來自android的參數?

EmailController.java

package com.intern.training 


import java.awt.PageAttributes.MediaType; 
import java.util.Map; 

import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 
import org.springframework.web.context.request.WebRequest; 

@RestController 
@RequestMapping("/email") 
public class EmailController 
{ 

    @RequestMapping(method= RequestMethod.GET) 
    public void getAll(WebRequest webRequest) 
    { 
     Map<String,String[]>params=webRequest.getParameterMap(); 
     System.out.println(params); 


    } 


} 

回答

1

我強烈建議你不要用GET發送請求的參數。優先請求POST。 (見Cross-site request forgery

然後,創建一個類,代表您要接收的參數:

public class RequestParams { 

    private String name; 
    private String surname; 

    //Getters, Setters... 

} 

然後想到這個對象作爲方法的設置了一個param:

@RequestMapping(method= RequestMethod.POST) 
/** 
    Pay attention to the above @RequestBody annotation 
    or you will get null instead of the parameters 
**/ 
public void getAll(@RequestBody RequestParams request) 
{ 
    request.getName(); 
    request.getSurname(); 
    //... 
    System.out.println(request.getName() + " " + request.getSurname()); 
} 
+0

但如何將接收來自android – programmingtech

+0

的參數假設名稱和姓氏是由android形式發送的參數,那麼如何在春天接收它 – programmingtech

+0

@programmingtech Android可以發送POST請求。如果您真的想要,您可以接受請求參數(請參閱@ RequestParam綁定),但我強烈建議您避免將其用於可能具有破壞性的請求。 –