`

通过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();
    }

}
分享到:
评论

相关推荐

    httpclient post方式发送请求

    总结起来,使用Apache HTTPClient库以POST方式发送JSON数据涉及的主要步骤包括:配置HttpClient实例、创建HttpPost对象、构建JSON实体、设置请求头和执行请求。通过这种方式,你可以方便地与Web服务进行交互,传递...

    HttpClientUtil工具类发送get和post请求,支持http和https,支持发送文件

    HttpClient是Java中用于执行HTTP请求的一个强大库,它提供了丰富的功能,可以方便地进行GET、POST请求,并且能够处理复杂的网络交互,包括发送文件等操作。下面我们将详细讨论HttpClientUtil工具类如何实现这些功能...

    HttpClient发送post请求传输json数据

    在这个场景中,我们关注的是如何使用HttpClient来发送POST请求并传输JSON数据。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于API接口的数据传递。 首先,我们需要引入Apache HttpClient...

    java 中HttpClient传输xml字符串实例详解

    至此,我们已经成功地使用Java的HttpClient库将一个对象转换为XML字符串,并以二进制流的方式发送到了服务器。这个过程中涉及的关键技术包括对象到XML的转换(JAXB)、流操作(ByteArrayOutputStream和...

    HttpClient发送http请求(post+get)需要的jar包+内符java代码案例+注解详解

    以下是一个使用HttpClient发送POST请求的Java代码示例: ```java import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import...

    http post 发送xml数据

    在IT行业中,HTTP POST方法是Web应用程序中向服务器发送数据的一种常见方式,特别是在涉及XML数据交换时。XML(可扩展标记语言)是一种用于结构化数据的标记语言,广泛用于网络通信和数据存储。本篇文章将深入探讨...

    使用HttpClient发送POST请求,并获取响应内容(附详细步骤).txt

    通过以上步骤,我们成功实现了使用Apache HttpClient发送POST请求并处理响应的过程。这对于与Web服务进行交互非常有用,尤其是在需要发送带有特定数据的请求时。希望本篇文章能帮助你在实际开发中更好地利用...

    httpclient发送post请求.docx

    执行POST请求是通过调用`httpClient`对象的`execute`方法实现的,它接收`HttpPost`对象作为参数,返回一个`CloseableHttpResponse`,代表服务器的响应。 ```java CloseableHttpResponse response = httpClient....

    JAVA发送HttpClient请求及接收请求完整代码实例

    在Java编程中,HttpClient是一个非常重要的工具,它允许开发者通过HTTP协议发送请求并接收服务器的响应。HttpClient库是由Apache软件基金会开发的,广泛应用于各种网络通信场景,包括数据的获取、上传、下载等。本篇...

    httpClient的xml,form,json提交

    在XML、form(表单数据)和JSON提交方面,HttpClient提供了一种灵活的方式将这些数据类型发送到服务器。 首先,我们来看`HttpClientUtil.java`,这是一个常见的工具类,通常包含一系列静态方法,用于简化HttpClient...

    HttpClient发送json、普通参数类型的Post请求(csdn)————程序.pdf

    本文主要讨论如何使用HttpClient发送JSON格式和普通参数类型的POST请求。首先,我们来看一下所需的Maven依赖。 ```xml &lt;groupId&gt;commons-httpclient &lt;artifactId&gt;commons-httpclient &lt;version&gt;3.1 &lt;groupId&gt;...

    webservice调用实例,通过HttpClient调用

    本示例将深入探讨如何使用Apache HttpClient库在Java环境中调用Web服务,特别是通过Maven构建项目的方式进行。HttpClient是一个强大的HTTP客户端编程工具包,能够支持多种HTTP协议特性,使得Web服务调用变得更加灵活...

    httppost和httpclient一组开发包

    4. 添加请求实体:通过`setEntity`方法设置请求的数据,如字符串、文件或表单数据。 5. 执行请求:调用`HttpClient`的`execute`方法,传入`HttpPost`对象,获取`HttpResponse`。 6. 处理响应:从`HttpResponse`中...

    HttpClient的简单使用,get、post、上传、下载

    总结,HttpClient是Java中强大的HTTP客户端工具,通过它我们可以方便地实现各种HTTP操作,包括简单的GET、POST请求,以及复杂的文件上传和下载。结合服务端的处理,可以构建出完整的网络通信解决方案。在实际使用中...

    以httpclient方式提交数据

    POST请求允许携带实体(Entity)作为请求体,可以是任何形式的数据,如文本、JSON、XML等。 4. **处理响应** 发送请求后,我们需要解析服务器返回的响应。HttpClient的`CloseableHttpResponse`对象提供了访问响应...

    Java访问.Net Webservice 通过httpclient SOAP实现

    4. **设置SOAP请求实体**:使用StringEntity或SoapEnvelope对象将构建的SOAP XML消息作为POST请求的实体内容。 5. **执行请求并处理响应**:通过HttpClient的execute方法发送请求,然后获取HttpRespose对象。从响应...

    httpclient-4.5.2.jar安卓网络请求

    4. 执行请求:使用HttpClient的`execute`方法发送请求,并获取响应: ```java CloseableHttpResponse response = httpClient.execute(httpGet); ``` 5. 处理响应:解析响应状态和内容,例如: ```java ...

    java发送JSON格式的http通讯的post请求

    `writeValueAsString()`方法将`MyData`对象转换为JSON字符串,然后通过`StringEntity`设置为POST请求的实体。 注意,处理HTTP响应时,需要确保正确关闭响应和HTTP客户端,以避免资源泄漏。 此外,如果你正在使用...

Global site tag (gtag.js) - Google Analytics