HttpClient发送Post请求,内容格式为xml,并获取响应内容

ErixHao 2012-11-23

ChannelDistributor.xml内容如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<request>

<userName>yisou</userName>

<pwd>abcd1234</pwd>

<channelCode>10010000</channelCode>

<insertType>00</insertType>

</request>

1).HttpClient发送Post请求,内容格式为xml,并获取响应内容

importjava.io.BufferedInputStream;

importjava.io.BufferedReader;

importjava.io.ByteArrayOutputStream;

importjava.io.FileNotFoundException;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.InputStreamReader;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.commons.httpclient.HttpClient;

importorg.apache.commons.httpclient.HttpStatus;

importorg.apache.commons.httpclient.methods.PostMethod;

importorg.apache.commons.httpclient.methods.StringRequestEntity;

importorg.apache.log4j.Logger;

publicclassServiceValidateextendsHttpServlet{

privateLoggerlog=Logger.getLogger(ServiceValidate.class);

privatestaticfinallongserialVersionUID=-6995391540735187530L;

@Override

protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)

throwsServletException,IOException{

this.doPost(req,resp);

}

/**

*发送xml数据请求到服务器端

*@paramurlxml请求数据地址

*@paramxmlString发送的xml数据流

*@returnnull发送失败,否则返回响应内容

*/

@Override

protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)

throwsServletException,IOException{

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");

Stringurl="http://localhost:8080/game/testServlet";

StringxmlString=getXmlString();

HttpClientclient=newHttpClient();

PostMethodmyPost=newPostMethod(url);

client.getParams().setSoTimeout(300*1000);

StringresponseString=null;

try{

myPost.setRequestEntity(newStringRequestEntity(xmlString,"text/xml","utf-8"));

intstatusCode=client.executeMethod(myPost);

if(statusCode==HttpStatus.SC_OK){

BufferedInputStreambis=newBufferedInputStream(myPost.getResponseBodyAsStream());

byte[]bytes=newbyte[1024];

ByteArrayOutputStreambos=newByteArrayOutputStream();

intcount=0;

while((count=bis.read(bytes))!=-1){

bos.write(bytes,0,count);

}

byte[]strByte=bos.toByteArray();

responseString=newString(strByte,0,strByte.length,"utf-8");

bos.close();

bis.close();

}

}catch(Exceptione){

log.error(e.getMessage(),e);

}

myPost.releaseConnection();

client.getHttpConnectionManager().closeIdleConnections(0);

System.out.println("responseString:"+responseString);

}

/**

*读取xml内容,将请求的xml

*保存成字符串进行post发送

*@return

*/

privateStringgetXmlString(){

StringBuildersb=newStringBuilder();

try{

InputStreaminputStream=ServiceValidate.class.getResourceAsStream("/ChannelDistributor.xml");

BufferedReaderbr=newBufferedReader(newInputStreamReader(inputStream));

Stringline="";

for(line=br.readLine();line!=null;line=br.readLine()){

sb.append(line+"\n");

}

}catch(FileNotFoundExceptione){

log.error(e.getMessage(),e);

}catch(IOExceptione){

log.error(e.getMessage(),e);

}

returnsb.toString();

}

@Override

protectedvoiddoPut(HttpServletRequestreq,HttpServletResponseresp)

throwsServletException,IOException{

this.doPost(req,resp);

}

}

2).获取HttpClientPost请求数据并响应内容

importorg.apache.log4j.Logger;

publicclassTestServletextendsHttpServlet{

privatestaticfinallongserialVersionUID=-6175353394519367540L;

privateLoggerlog=Logger.getLogger(TestServlet.class);

@Override

protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)

throwsServletException,IOException{

this.doPost(req,resp);

}

@Override

protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)

throwsServletException,IOException{

try{

intlen=request.getContentLength();

System.out.println("数据流长度:"+len);

//获取HTTP请求的输入流

InputStreamis=request.getInputStream();

//已HTTP请求输入流建立一个BufferedReader对象

BufferedReaderbr=newBufferedReader(newInputStreamReader(is,"UTF-8"));

//读取HTTP请求内容

Stringbuffer=null;

StringBuffersb=newStringBuffer();

while((buffer=br.readLine())!=null){

//在页面中显示读取到的请求参数

sb.append(buffer+"\n");

}

System.out.println("接收post发送数据:\n"+sb.toString().trim());

PrintWriterout=response.getWriter();

StringBufferstringBuffer=newStringBuffer("<?xmlversion=\"1.0\"encoding=\"UTF-8\"?>");

stringBuffer.append("<response>");

stringBuffer.append("<status>800</status>");

stringBuffer.append("<tokenPwd>jkuiowerncxuidafjkfdaouifdaljkn</tokenPwd>");

stringBuffer.append("</response>");

out.write(stringBuffer.toString());

out.flush();

out.close();

}catch(Exceptione){

log.error(e.getMessage(),e);

}

}

}

控制台输出如下:

数据流长度:175

接收post发送数据:

<?xmlversion="1.0"encoding="UTF-8"?>

<request>

<userName>yisou</userName>

<pwd>abcd1234</pwd>

<channelCode>10010000</channelCode>

<insertType>00</insertType>

</request>

responseString:<?xmlversion="1.0"encoding="UTF-8"?><response><status>800</status><tokenPwd>jkuiowerncxuidafjkfdaouifdaljkn</tokenPwd></response>

相关推荐