RestTemplate例子

RestTemplate的一个例子,很简单。更多RestTemplate的内容请看附件。

pom.xml

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.3.5</version>
</dependency>

spring的xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:sec="http://www.springframework.org/schema/security"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"

	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">


	<bean id="template" class="org.springframework.web.client.RestTemplate">
		<constructor-arg>
			<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"/>
		</constructor-arg>
	</bean>

	
</beans>

Java类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <pre>
 * ExampleRestTemplate.java
 * @author kanpiaoxue<br>
 * @version 1.0
 * Create Time 2014年9月1日 下午4:21:51<br>
 * Description : RestTemplate例子
 * </pre>
 */
public class ExampleRestTemplate {

    /**
     * <pre>
     * @param args
     * </pre>
     */
    public static void main(String[] args) {

        RestTemplate template = new RestTemplate(
                new HttpComponentsClientHttpRequestFactory());
        String rs = template
                .getForObject(
                        "http://localhost:8080/dmap-console/web/config/test?message={message}",
                        String.class, "hello");
        System.out.println(rs);

        // spring start
        @SuppressWarnings("resource")
        ApplicationContext context = new FileSystemXmlApplicationContext(
                "D:/spring/restTemplate/spring-ctx-application.xml");
        final RestTemplate template1 = context.getBean("template",
                RestTemplate.class);

        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0, j = Runtime.getRuntime().availableProcessors() * 2; i < j; i++) {
            exec.execute(new Runnable() {

                @Override
                public void run() {

                    for (int n = 0; n < 10000; n++) {
                        String rs1 = template1
                                .getForObject(
                                        "http://localhost:8080/dmap-console/web/config/test?message={message}",
                                        String.class, "hello");
                        System.out.println(rs1);
                    }

                }
            });
        }
        exec.shutdown();
    }

}

使用get请求,携带http header信息:

    public Result<Void> clearApiServerCache() {
        LOGGER.info("start to clearApiServerCache.");
        String url = "http://www.kanpiaoxue.org/team/clearAllTeamCache";        
        HttpHeaders headers = new HttpHeaders();
        headers.set("auth_token", "34qwljfalfjdl");
        headers.setContentType(MediaType.APPLICATION_JSON);
// application/json

        HttpEntity<String> entity = new HttpEntity<String>(headers);
        HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        LOGGER.info("clearApiServerCache response:{}", response);
        Type typeOfT = new TypeToken<Result<Void>>() {
        }.getType();
        Result<Void> rs = new GsonBuilder().create().fromJson(response.getBody(), typeOfT);
        LOGGER.info("finish clearApiServerCache. rs:{}", rs);
        return rs;
    }
 

参考地址: http://www.cnblogs.com/tomcatandjerry/p/5899722.html

猜你喜欢

转载自kanpiaoxue.iteye.com/blog/2111780