美文网首页
发送xml格式的post请求

发送xml格式的post请求

作者: 在路上的CT | 来源:发表于2017-09-25 15:43 被阅读33次

maven:

<dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
</dependency>

关键代码:

HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("http://demo.com");
client.getParams().setSoTimeout(300 * 1000);
// 返回结果
String result = null;
try {
    // 置请求体为xml格式的字符串
    myPost.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
    int statusCode = client.executeMethod(postMethod);
    if (statusCode == HttpStatus.SC_OK) {
        BufferedInputStream bis = new BufferedInputStream(postMethod.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();
        result = new String(strByte, 0, strByte.length, "utf-8");
        bos.close();
        bis.close();
    }
} catch (Exception e) {
    e.printStackTrace();
}
// 需要释放掉、关闭连接
myPost.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
System.out.println(result );

相关文章

网友评论

      本文标题:发送xml格式的post请求

      本文链接:https://www.haomeiwen.com/subject/djkdextx.html