http post 接口

集团需求管理系统通过网状网与给各省公司需求管理系统进行交互。落地方为发起方提供访问的URL,发起方使用HTTP POST方法发送请求报文并得到应答报文,发起方作为落地方的HTTP客户端,落地方作为发起方的HTTP服务器。因此,各个参与方需要同时实现HTTP客户端以及服务器的功能。

在HTTP传输过程中,HTTP Header部分需要遵循下面的约定:

在请求报文中:content-type=multipart/form-data

在应答报文中:content-type=multipart/mixed

HTTP交易报文需要遵循以下约定,报文头的parameter名为“xmlhead”;报文体的parameter名为“xmlbody”。


落地方即服务端代码

写一个servlet


PlatFormFilter
com.asiainfo.aibsm.platform.inter.PlatFormServlet


PlatFormFilter
/platformService


在PlatFormServlet.java 的doPost(HttpServletRequest req, HttpServletResponse resp)方法中写一下逻辑

Map params = new HashMap();
FileItemFactory factory = new DiskFileItemFactory();//具体使用参考我的博客FileItemFactory类
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest( req );
Iterator iter = items.iterator();
while (iter.hasNext()) 
{
FileItem item = (FileItem) iter.next();
if (item.isFormField()) 
{
String name = item.getFieldName();
String value = item.getString("UTF-8");
params.put( name.toUpperCase(), value.trim());

}


String xmlhead = params.get( "XMLHEAD" ).toString();//报文头
String xmlbody = params.get( "XMLBODY" ).toString();//报文体


String responsXML = srv.getResponsesXML( xmlhead , xmlbody ); //  获取返回报文

//回复报文
this.log.info("应答报文:" + responsXML);
resp.setContentType("multipart/mixed");
resp.setCharacterEncoding("utf-8");
resp.getWriter().write( responsXML );



发起方即客户端代码

public static String postUrl( String url, Map xmlheadMap, String xmlbody )
{
PostMethod post = null;
String respon = null;
String xmlhead = null;
try
{
xmlhead = getxmlhead( xmlheadMap );//报文头
log.info("开始访问:" + url );//服务端url
log.info( "xmlhead:" + xmlhead );
log.info( "xmlbody:" + xmlbody );

xmlbody = new String(xmlbody.getBytes("UTF-8"),"ISO-8859-1");//报文体 转成iso-8859-1
HttpClient client = new HttpClient();
post = getPostMethod(url, xmlhead , xmlbody );
client.getParams().setParameter("http.protocol.version",HttpVersion.HTTP_1_1);
// client.getParams().setParameter("http.protocol.content-charset","UTF-8");

client.executeMethod( post );
respon = post.getResponseBodyAsString();
log.info("应答报文:" + respon );
log.info("访问结束:" + url );
}
catch(Exception e)
{
e.printStackTrace();
}
finally
        {
            // 释放连接
post.releaseConnection();
         }
return respon;
}

private static PostMethod getPostMethod(  String url, String xmlhead, String xmlbody ) throws Exception 
{
PostMethod post = new PostMethod(url);
List partList = new ArrayList();
partList.add(new StringPart("xmlhead", xmlhead, "UTF-8"));
partList.add(new StringPart("xmlbody", xmlbody, "UTF-8"));

//参考MultipartRequestEntity 类
MultipartRequestEntity multiEnt = new MultipartRequestEntity(
partList.toArray(new Part[partList.size()]),
post.getParams());
post.setRequestEntity(multiEnt);
return post;


}

你可能感兴趣的:(java)