HttpClient4 Post XML数据
最近项目中用到SOAP,要求客户端POST SOAP数据过去,整理一下自己写的东西。
POST XML一般有两种方法,一种是指定参数名,将该参数来进行XML数据的传输,这是最常用的一种方式。
这次我想说明的另外一种,直接将XML数据以流的方式写入请求。
Servlet POST方法中来接受传送过来的XML流:
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.setContentType("text/xml");
- response.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- System.out.println("----------------------");
- BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
- String line = null;
- StringBuffer sb = new StringBuffer();
- while ((line = reader.readLine()) != null) {
- sb.append(line).append("\r\n");
- }
- System.out.println(sb.toString());
- System.out.println("----------------------");
- out.print(sb.toString());
- out.flush();
- out.close();
- }
Client端POST XML过去:
- package com.javaeye.wangking717.util;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.DefaultHttpClient;
- public class HttpConnectionUtil {
- private final static Log logger = LogFactory.getLog(HttpConnectionUtil.class);
- public static String postSOAP(String url, String soapContent) {
- HttpClient httpclient = null;
- HttpPost httpPost = null;
- BufferedReader reader = null;
- int i = 0;
- while (i < 4) {
- try {
- httpclient = new DefaultHttpClient();
- httpPost = new HttpPost(url);
- StringEntity myEntity = new StringEntity(soapContent, "UTF-8");
- httpPost.addHeader("Content-Type", "text/xml; charset=UTF-8");
- httpPost.setEntity(myEntity);
- HttpResponse response = httpclient.execute(httpPost);
- HttpEntity resEntity = response.getEntity();
- if (resEntity != null) {
- reader = new BufferedReader(new InputStreamReader(resEntity
- .getContent(), "UTF-8"));
- StringBuffer sb = new StringBuffer();
- String line = null;
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- sb.append("\r\n");
- }
- return sb.toString();
- }
- } catch (Exception e) {
- i++;
- if (i == 4) {
- logger.error("not connect:" + url + "\n" + e.getMessage());
- }
- } finally {
- if (httpPost != null) {
- httpPost.abort();
- }
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (httpclient != null) {
- httpclient.getConnectionManager().shutdown();
- }
- }
- }
- return "none";
- }
- public static void main(String[] args) {
- String url = "http://localhost:8080/opgtest/servlet/MyTest";
- String soap = "<xml>\r\n"
- + "<body>\r\n"
- + "传递过来的内容\r\n"
- + "</body>\r\n"
- + "</xml>";
- System.out.println(postSOAP(url, soap));
- }
- }