Httpclient 发送XML

该博客介绍了如何在Java中利用Apache HttpClient库发送XML数据的HTTP POST请求。首先定义了XML的头部信息,然后创建XML字符串,接着通过DefaultHttpClient实例创建HttpPost对象,并设置请求头和XML实体。最后执行请求并获取响应状态码。
摘要由CSDN通过智能技术生成

package com.actions;

public interface IClient {
 
 public String XML_HEADER = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";

 

}

package com.actions;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class XMLClient {
 
 private DefaultHttpClient client;

 public String getXMLString() {
   StringBuffer sb = new StringBuffer();
    sb.append(IClient.XML_HEADER);
    sb.append("<AastraIPPhoneInputScreen type=\"string\">");
    sb.append("<Title>Hello world!</Title>");
    sb.append("<Prompt>Enter value</Prompt>");
    sb.append("<URL>http://localhost/xmlserver/test.do</URL>");
    sb.append("<Parameter>value</Parameter>");
    sb.append("<Default></Default>");
    sb.append("</AastraIPPhoneInputScreen>");
    return sb.toString();
  }
 public Integer sendXMLDataByPost(String url, String xmlData)throws ClientProtocolException, IOException {
       Integer statusCode = -1;
       if (client == null) {
    client = new DefaultHttpClient();
   }
      HttpPost post = new HttpPost(url);
      StringEntity entity = new StringEntity(xmlData);
      post.setEntity(entity);
      post.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
      HttpResponse response = client.execute(post);
      statusCode = response.getStatusLine().getStatusCode();
      return statusCode;
 }

 public void testAA() throws ClientProtocolException, IOException {
     XMLClient client = new XMLClient();
     Integer statusCode = client.sendXMLDataByPost("http://localhost:8080/testhttp/test", client.getXMLString());
     if(statusCode==200){
      System.out.println("Request Success,Response Success!!!");
     }else{
      System.out.println("Response Code :"+statusCode);
     }


 
 
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值