java rest 调用_Java调用Restful之RestTemplate
1.spring-mvc.xml中增加RestTemplate的配置
2.引入相關(guān)jar包
httpclient-4.3.3.jar、httpcore-4.3.2.jar,jar包版本根據(jù)需求自行調(diào)整。
3.Controller中使用import java.util.HashMap; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; import net.sf.json.JSONObject; @Controller public class RestTestController { //注入restTemplate @Autowired private RestTemplate restTemplate; /** * restful接口測(cè)試 * @return */ @RequestMapping(value = "/restTest") public String restTest(Model model){ //restful請(qǐng)求地址 String url = "http://127.0.0.1:8081/demo/contact/getContactDb"; String json = restTemplate.getForObject(url, String.class); JSONObject obj = JSONObject.fromObject(json); String state = (String) obj.get("state"); System.out.println(json); try { } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "main/test"; } }
總結(jié)
以上是生活随笔為你收集整理的java rest 调用_Java调用Restful之RestTemplate的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php取消mysql警告_mysql登录
- 下一篇: java与c应用,Java和C应用程序之