`

通过HttpClient以Post方式发送Http请求,请求实体是XML

阅读更多
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 {
    /**
     * 
     * 以Post方式发送Http请求,请求实体是XML <br>
     * 〈功能详细描述〉
     * 
     * @throws IOException
     * @throws ClientProtocolException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @Test
    public void postHttpRequest(){
        //发送的报文,请求的报文也要根据实际的业务进行封装,这里暂时是写死的
        String requestXml="<MbfService>"+
                              "<input1>"+
                                "<MbfHeader>"+
                                  "<ServiceCode>1</ServiceCode>"+
                                  "<Operation>1</Operation>"+
                                  "<AppCode>1</AppCode>"+
                                  "<UId>1</UId>"+
                                  "<AuthId>1</AuthId>"+
                                "</MbfHeader>"+
                                "<MbfBody>"+
                                  "<provinceQuery>"+
                                        "<provinceCode>1</provinceCode>"+
                                        "<provinceName>1</provinceName>"+
                                  "</provinceQuery>"+
                                "</MbfBody>"+
                              "</input1>"+
                            "</MbfService>";
        HttpPost httpPost = null;

        try {
            // 定义HttpPost请求
            httpPost = new HttpPost("http://lxf.cnsuning.com:8080/sel-web/cm/testPostRequest.action");
            // 定义请求实体
            HttpEntity requestEntity = new StringEntity(requestXml, "UTF-8");
            httpPost.setEntity(requestEntity);

            // 定义HttpClient
            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);

            // 以post方式发送Http请求
            HttpResponse httpResponse = httpClient.execute(httpPost);

            // 获取响应实体
            HttpEntity responsetEntity = httpResponse.getEntity();
            InputStream inputStream = responsetEntity.getContent();

            StringBuilder reponseXml = new StringBuilder();
            byte[] b = new byte[2048];
            int length = 0;
            while ((length = inputStream.read(b)) != -1) {
                reponseXml.append(new String(b, 0, length));
            }
            System.out.println(reponseXml);
        } catch (Exception e) {
            //释放请求的连接
            if(httpPost!=null){
                httpPost.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.io.InputStream;
import java.util.HashMap;
import java.util.Map;

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

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

import com.suning.sop.datatype.StringUtil;

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

    /**
     * 
     * 测试post请求 <br>
     * 〈功能详细描述〉
     * 
     * @param request
     * @param reponse
     * @throws IOException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "testPostRequest.action")
    public void testPostRequest(HttpServletRequest request, HttpServletResponse reponse) throws IOException {
        // 获取请求的报文
        String xmlStr = getRequestXml(request);
        if (!StringUtil.isEmpty(xmlStr)) {
            // 将请求报文转化为Map对象
            Map<String, Object> params = convertXmlToMap(xmlStr);
            System.out.println(params);

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

            // 返回响应的报文
            reponse.getOutputStream().write(responseXml.getBytes());
        }
    }

    /**
     * 
     * 将请求的报文转化为Map对象 <br>
     * 〈功能详细描述〉
     * 
     * @param xmlStr
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private Map<String, Object> convertXmlToMap(String xmlStr) {
        Map<String, Object> params = new HashMap<String, Object>();
        return params;
    }

  
    /**
     * 
     * 获取请求的报文 <br>
     * 〈功能详细描述〉
     * 
     * @param request
     * @return
     * @throws IOException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getRequestXml(HttpServletRequest request) throws IOException {
        InputStream inputStream = request.getInputStream();

        StringBuffer requestXml = new StringBuffer();
        byte[] b = new byte[2048];
        int length = 0;
        while ((length = inputStream.read(b)) != -1) {
            requestXml.append(new String(b, 0, length));
        }
        return requestXml.toString();
    }

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics