`

通过HttpClient测试Get请求,无请求实体,仅仅是通过URL发送请求

阅读更多
web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	version="2.4"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<!-- spring 监听-->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- spring 字符集过滤 -->
	<filter>
		<filter-name>CharacterEncoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncoding</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>
	
	<filter-mapping>
		<filter-name>CharacterEncoding</filter-name>
		<url-pattern>*.htm</url-pattern>
	</filter-mapping>
	
	
	<!-- spring mvc -->
	<servlet>
		<servlet-name>http</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:conf/freemarker-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>http</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
	
	<servlet-mapping>
		<servlet-name>http</servlet-name>
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>

	<session-config>
		<session-timeout>120</session-timeout>
	</session-config>

	<!-- welcome file -->
	<welcome-file-list>
		<welcome-file>homePage.htm</welcome-file>
	</welcome-file-list>

	<!-- error-page -->
	<error-page>
		<!-- 400错误 请求无效 --> 
		<error-code>400</error-code>
		<location>/400.htm</location>
	</error-page>
	<error-page>
		<!-- 404页面不存在 --> 
		<error-code>404</error-code>
		<location>/404.htm</location>
	</error-page>
	<error-page>
		<!-- 405无效链接 --> 
		<error-code>405</error-code>
		<location>/405.htm</location>
	</error-page>
	<error-page>
		<!-- 500 服务器内部错误 --> 
		<error-code>500</error-code>
		<location>/500.htm</location>
	</error-page>
	
</web-app>


applicationContext.xml配置文件:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd"
	default-lazy-init="false">

	<!-- 资源文件 -->
	<context:property-placeholder location="classpath:/conf/setting-web.properties" />
	
	<!-- DB2 dataSource-->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
	
	<!-- 定义事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="insert*" propagation="REQUIRED" read-only="false"
				rollback-for="java.lang.Exception" />
			<tx:method name="save*" propagation="REQUIRED" read-only="false"
				rollback-for="java.lang.Exception" />
			<tx:method name="update*" propagation="REQUIRED" read-only="false"
				rollback-for="java.lang.Exception" />
			<tx:method name="modify*" propagation="REQUIRED" read-only="false"
				rollback-for="java.lang.Exception" />
			<tx:method name="delete*" propagation="REQUIRED" read-only="false"
				rollback-for="java.lang.Exception" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="select*" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>

	<aop:config>
		<aop:pointcut id="bizMethods"
			expression="execution(* org.apache.ecity.*.service.*.*(..)) or execution(* org.apache.ecity.*.*.service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="bizMethods" />
	</aop:config>
	
	<!-- service 层Bean -->
	<import resource="classpath*:/conf/bean/*-bean.xml" />
	
	<context:annotation-config />
</beans>



freemarker-servlet.xml SpringMVC配置文件:
<?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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 引入资源文件 -->
	<context:property-placeholder location="classpath:/conf/setting-web.properties" />
	
	<!-- Spring 扫描使用注解的包路径 -->
	<context:component-scan
		base-package="org.apache.remote.httpclient" />

	<!-- 注解依赖的适配器 AnnotationMethodHandlerAdapter -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>

	<!-- 注解依赖的适配器 DefaultAnnotationHandlerMapping -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
	</bean>

	<!-- Spring @AutoWired 依赖自动注入,不需要setter方法 -->
	<bean
		class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
	
	<!-- FreeMarker模板配置 -->
	<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<!-- FreeMarker模板路径前缀,Controller方法返回FTL文件路径是可以省略前缀,比如/WEB-INF/ftl/sys/province/main.ftl,只需要返回 sys/province/main-->
		<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>
	
	<!-- FreeMarker视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="cache" value="true" />
		<property name="prefix" value="" />
		<property name="suffix" value=".ftl" />
		<property name="exposeSpringMacroHelpers" value="true" />
		<property name="exposeRequestAttributes" value="true" />
		<property name="exposeSessionAttributes" value="true" />
		<property name="requestContextAttribute" value="request" />
		<property name="contentType" value="text/html; charset=utf-8" />
	</bean>

	<!-- Spring JSON 格式转换依赖的Jar -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

</beans>



import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.testng.annotations.Test;
/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 * 
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class HttpClientTest {
    
    /**
     * 
     * 测试Get请求,无请求实体,仅仅是通过URL发送请求 <br>
     * 〈功能详细描述〉
     *
     * @throws RscException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @Test
    public void testGetHttpRequest(){
        
        HttpGet httpGet=new HttpGet("http://lxf.cnsuning.com:8080/sel-web/cm/tesGetRequest.action?param1=1&param1=2&param3=3");
        
        try {
            HttpClient httpClient=new DefaultHttpClient();
            HttpParams httpParams= httpClient.getParams();
            // 设置Http协议的版本
            httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            // 设置请求连接超时时间
            httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
            // 设置请求响应超时时间
            httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
            
            //以Get方式发送Http请求
            HttpResponse httpResponse=httpClient.execute(httpGet);
            HttpEntity httpEntity=httpResponse.getEntity();
            InputStream inputStream=httpEntity.getContent();
            
            byte[] b=new byte[2048];
            int length=0;
            StringBuffer responseContent=new StringBuffer();
            while((length=inputStream.read(b))!=-1){
                responseContent.append(new String(b,0,length));
            }
            
            System.out.println(responseContent.toString());
            
        } catch (Exception e) {
            //释放连接
            if(httpGet!=null){
                httpGet.abort();
            }
            
            if(SocketTimeoutException.class.isInstance(e)){
                throw new RuntimeException("Http请求响应超时",e);
            }
            else if(ConnectTimeoutException.class.isInstance(e)){
                throw new RuntimeException("Http请求连接超时", e);
            }
            else if(ConnectException.class.isInstance(e)){
                throw new RuntimeException("Http请求异常", e);
            }else{
                throw new RuntimeException("其他异常", e);
            }
        }
    }
}




import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping(value = "/cm")
@Controller
@SuppressWarnings("unchecked")
public class TestHttpClientController {

    /**
     * 
     * 测试get请求 <br>
     * 〈功能详细描述〉
     * 
     * @param request
     * @param reponse
     * @throws IOException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "tesGetRequest.action")
    public void tesGetRequest(HttpServletRequest request, HttpServletResponse reponse) throws IOException {
        // 获取请求参数
        Map params = getRequestMap(request);
        System.out.println(params);

        // 响应的报文,需要根据业务去拼装响应报文
        String responseXml = "响应报文";

        // 返回响应报文,响应报文要根据实际业务来决定是否返回响应报文给请求方
        reponse.getOutputStream().write(responseXml.getBytes());
    }

    /**
     * 
     * 根据request将请求参数转化为Map<br>
     * 〈功能详细描述〉
     * 
     * @param request
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @SuppressWarnings("rawtypes")
    private Map<String, Object> getRequestMap(HttpServletRequest request) {
        // 获取请求参数
        Map parameterMap = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entrySet = parameterMap.entrySet();

        // 定义转化后的请求Map
        Map<String, Object> params = new HashMap<String, Object>();
        for (Entry<String, String[]> entry : entrySet) {
            // 如果请求的参数的值是数组
            if (entry.getValue().length > 1) {
                params.put(entry.getKey(), entry.getValue());
            } else {
                params.put(entry.getKey(), entry.getValue()[0]);
            }
        }

        return params;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics