java向http接口发送请求并接收返回数据

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.css.apps.base.dict.service.DictMan;

public class sendHttp{
	private static Logger log = Logger.getLogger(sendHttp.class);
	public static Map<String, List<String>> a = new HashMap<String, List<String>>();
	public static List<String> nodeNameList = new ArrayList<>();
	 public static Map sendHttpTest(String loginName,String flag,String number) throws IOException{ 
		 	Map c = new HashMap();
	        //关闭   
	        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");     
	        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");     
	        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");    
	          
	        //创建httpclient工具对象   
	        HttpClient client = new HttpClient();    
	        //创建post请求方法   
	        String urlstr = "";
	        PostMethod myPost = new PostMethod(urlstr);  
	        //设置请求超时时间   
	        client.setConnectionTimeout(300*1000);  
	        String responseString = null;    
	        try{    
	            //设置请求头部类型   
	            myPost.setRequestHeader("Content-Type","text/xml");  
	            myPost.setRequestHeader("charset","utf-8");  
	              
	            //设置请求体,即xml文本内容,注:这里写了两种方式,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式   
	            String xmlString = getXmlInfo(loginName,number);
	            myPost.setRequestBody(xmlString);   
	            myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8"));     
	            int statusCode = client.executeMethod(myPost);    
	            if(statusCode == HttpStatus.SC_OK){    
	                BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());    
	                byte[] bytes = new byte[1024];    
	                ByteArrayOutputStream bos = new ByteArrayOutputStream();    
	                int count = 0;    
	                while((count = bis.read(bytes))!= -1){    
	                    bos.write(bytes, 0, count);    
	                }    
	                byte[] strByte = bos.toByteArray();    
	                responseString = new String(strByte,0,strByte.length,"utf-8");    
	                bos.close();    
	                bis.close();    
	            }    
	        }catch (Exception e) {    
	            e.printStackTrace();    
	        }    
	        myPost.releaseConnection();    
	        c = convertXmlToMap(responseString);
	        return c;    
	    }    

	 	/**
		 * xml报文转换为map
		 * @author lpx
		 */
	    
		public static Map<String, List<String>> convertXmlToMap(String xmldata){
			Map<String, List<String>> map=new HashMap<String, List<String>>();
		    Document doc=null;
		    try {
		    	//将字符串转换为doc
				doc=DocumentHelper.parseText(xmldata);
				//获取根节点
				Element root=doc.getRootElement();
				map=getNodes(root);
				nodeNameList = new ArrayList<>();
			} catch (Exception e) {
				e.printStackTrace();
			}
		  
			return map;
			
		}
		/** 
	     * 从指定节点Element node开始,递归遍历其所有子节点 
	     */  
	    @SuppressWarnings("unchecked")
		public static Map<String, List<String>> getNodes(Element node) {
	        // 当前节点的名称、文本内容和属性  
	        String nodeName = node.getName();// 当前节点名称  
	        String nodeText = node.getTextTrim();// 当前节点内容
	       //节点名为messageText加入map中去
	       if(!node.getTextTrim().isEmpty() && "messageText".equals(nodeName)){
	    	   nodeNameList.add(nodeText);
	    	   a.put("messageText",nodeNameList);
	       }
	       // 递归遍历当前节点所有的子节点  
	        final List<Element> listElement = node.elements();// 所有一级子节点的list  
	        for (final Element e : listElement) {// 遍历所有一级子节点  
	            getNodes(e);// 递归
	        }
	        return a;  
	    } 
	    private static String getXmlInfo(String loginName,String number) {
			StringBuilder sb = new StringBuilder();
			sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			sb.append("<Root>");
			sb.append("<Document>");
			sb.append("<LoginName>"
					+ loginName
					+ "</LoginName>");
			sb.append("<Number>"
					+ number
					+ "</Number>");
			sb.append("</Document>");
			sb.append("</Root>");
			return sb.toString();
		}
}

 

转载于:https://my.oschina.net/u/3748375/blog/3081640

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值