Java调用Restful之RestTemplate

匿名 (未验证) 提交于 2019-12-02 21:53:52

1.spring-mvc.xml中增加RestTemplate的配置

<!-- 配置RestTemplate -->     <!--Http client Factory -->     <bean id="httpClientFactory"         class="org.springframework.http.client.SimpleClientHttpRequestFactory">         <property name="connectTimeout" value="10000" />         <property name="readTimeout" value="10000" />     </bean>      <!--RestTemplate -->     <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">         <constructor-arg ref="httpClientFactory" />     </bean>

2.引入相关jar包

httpclient-4.3.3.jar、httpcore-4.3.2.jar,jar包版本根据需求自行调整。

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接口测试 	 * @return 	 */ 	@RequestMapping(value = "/restTest") 	public String restTest(Model model){ 		//restful请求地址 		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"; 	} } 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!