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"; } }