httpclient发送post xml请求参数据,对响应的xml做处理

httpclient发送xml的请求参数,查询到的数据也是xml,然后做处理,插入数据库

一.拼接发送的xml请求参数

  1.1 定义一个实体类

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getProductRequest", propOrder = {
    "SecretKey",
    "Type",
    "ProductIDs"
})
public class GetProductRequest {
	@XmlElement(name = "SecretKey")
	private String SecretKey;
	@XmlElement(name = "Type")
	private Integer Type;
	@XmlElementWrapper(name="ProductIDs") 
    @XmlElement(name="ProductID") 
	private List ProductIDs;
	public String getSecretKey() {
		return SecretKey;
	}
	public void setSecretKey(String secretKey) {
		SecretKey = secretKey;
	}
	public Integer getType() {
		return Type;
	}
	public void setType(Integer type) {
		Type = type;
	}
	public List getProductIDs() {
		return ProductIDs;
	}
	public void setProductIDs(List productIDs) {
		ProductIDs = productIDs;
	}
}

1.2把请求的参数对应的封装到实体类里面,然后实体类转换成xml字符串

public  static String objectToXml(Object value) {
		String str = null;
		JAXBContext context = null;
	    StringWriter writer = null;
		try {
		    context = JAXBContext.newInstance(value.getClass());
			Marshaller mar = context.createMarshaller();
	        writer = new StringWriter();
	        mar.marshal(value, writer);
	        str = writer.toString().replace("getProductRequest", "GetProductRequest");
		} catch (JAXBException e) {
			e.printStackTrace();
		}finally {
			if(context != null) context = null;
			if(writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				writer = null;
			}
		}
	    
        return str;
	}
ps:writer.toString().replace("getProductRequest", "GetProductRequest");

这里的为什么要替换这个呢?不知道为什么对象转xml的时候那个标签本身是大写的,变成小写了。我这边如果是小写的话,就不能发送请求,400 如果是大写的,就是200,所以我为了方便,直接这样子改了一下

二.创建httpclient,发送请求

  2.1封装一个发送httpclient的方法,会得到响应

/**  
     * 发送xml请求到server端  
     * @param url xml请求数据地址  
     * @param xmlString 发送的xml数据流  
     * @return null发送失败,否则返回响应内容  
     */    
    public static String sendPost(String url,String xmlString){    
        //创建httpclient工具对象   
        HttpClient client = new HttpClient();    
        //创建post请求方法   
        PostMethod myPost = new PostMethod(url);    
        //设置请求超时时间   
        client.setConnectionTimeout(3000*1000);  
        String responseString = null;    
        try{    
            //设置请求头部类型   
            myPost.setRequestHeader("Content-Type","text/xml");  
            myPost.setRequestHeader("charset","utf-8");  
            //设置请求体,即xml文本内容,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式   
            myPost.setRequestBody(xmlString);   
            int statusCode = client.executeMethod(myPost);   
            //只有请求成功200了,才做处理
            if(statusCode == HttpStatus.SC_OK){    
            	InputStream inputStream = myPost.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                StringBuffer stringBuffer = new StringBuffer();
                String str = "";
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                responseString = stringBuffer.toString();
            }    
        }catch (Exception e) { 
            e.printStackTrace();    
        }finally{
        	 myPost.releaseConnection(); 
        }
        return responseString;    
    }   

 ps:BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));这里的字符输入流必须要utf-8加一下,要不然乱码

2.2因为得到的是xml文件,所以需要把str转换成document,我这里用到的是dom4j来进行操作的

			Document document = null;
			try {
				 document = DocumentHelper.parseText(responseStr);  
			} catch (DocumentException e) {
				e.printStackTrace();
			}catch (Exception e1){
				e1.printStackTrace();
			}

2.3后面只要对document得到的数据进行处理就行了

完成

记录一下。



你可能感兴趣的:(整理)