通过原生的java Http请求soap发布接口

package com.aiait.ivs.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

public class HttpUtil {
    private static final Logger logger = Logger.getLogger(HttpUtil.class);

    //请求soap接口用这个方法
    public static String soapPostSendXml(String SOAPUrl,String parXmlInfo){
          StringBuilder result = new StringBuilder();
          try {
              String SOAPAction = "submitMs";
              // Create the connection where we‘re going to send the file.
              URL url = new URL(SOAPUrl);
              URLConnection connection = url.openConnection();
              HttpURLConnection httpConn = (HttpURLConnection) connection;
              // how big it is so that we can set the HTTP Cotent-Length
              // property. (See complete e-mail below for more on this.)
              // byte[] b = bout.toByteArray();
              byte[] b = parXmlInfo.getBytes("ISO-8859-1");
              // Set the appropriate HTTP parameters.
              httpConn.setRequestProperty( "Content-Length",String.valueOf( b.length ) );
              httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
              httpConn.setRequestProperty("SOAPAction",SOAPAction);
              httpConn.setRequestMethod( "POST" );
              httpConn.setDoOutput(true);
              httpConn.setDoInput(true);

              // Everything‘s set up; send the XML that was read in to b.
              OutputStream out = httpConn.getOutputStream();
              out.write( b );
              out.close();
              // Read the response and write it to standard out.
              InputStreamReader isr =new InputStreamReader(httpConn.getInputStream());
              BufferedReader in = new BufferedReader(isr);
              String inputLine;
              while ((inputLine = in.readLine()) != null)
                      result.append(inputLine);
              in.close();

          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
          logger.info("\n soap respone \n"+result);
          return result.toString();
      }

      public static String readTxtFile(String filePath){
          StringBuilder result = new StringBuilder();
          try {

                  String encoding="GBK";

                  File file=new File(filePath);

                  if(file.isFile() && file.exists()){ //判断文件是否存在

                      InputStreamReader read = new InputStreamReader(

                      new FileInputStream(file),encoding);//考虑到编码格式

                      BufferedReader bufferedReader = new BufferedReader(read);

                      String lineTxt=null;

                      while((lineTxt = bufferedReader.readLine()) != null){
                          result.append(lineTxt);
                          System.out.println(lineTxt);

                      }

                      read.close();

          }else{

              System.out.println("找不到指定的文件");

          }

          } catch (Exception e) {

              System.out.println("读取文件内容出错");

              e.printStackTrace();

          }

          return result.toString();
      }

    /**
     * http post请求
     * @param url                        地址
     * @param postContent                post内容格式为param1=value?m2=value2?m3=value3
     * @return
     * @throws IOException
     */
    public static String httpPostRequest(URL url, String postContent) throws Exception{
        OutputStream outputstream = null;
        BufferedReader in = null;
        try
        {
            URLConnection httpurlconnection = url.openConnection();
            httpurlconnection.setConnectTimeout(10 * 1000);
            httpurlconnection.setDoOutput(true);
            httpurlconnection.setUseCaches(false);
            OutputStreamWriter out = new OutputStreamWriter(httpurlconnection
                    .getOutputStream(), "UTF-8");
            out.write(postContent);
            out.flush();

            StringBuffer result = new StringBuffer();
            in = new BufferedReader(new InputStreamReader(httpurlconnection
                    .getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            return result.toString();
        }
        catch(Exception ex){
            logger.error("post请求异常:" + ex.getMessage());
            throw new Exception("post请求异常:" + ex.getMessage());
        }
        finally
        {
            if (outputstream != null)
            {
                try
                {
                    outputstream.close();
                }
                catch (IOException e)
                {
                    outputstream = null;
                }
            }
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    in = null;
                }
            }
        }
    }    

    /**
     * 通过httpClient进行post提交
     * @param url                提交url地址
     * @param charset            字符集
     * @param keys                参数名
     * @param values            参数值
     * @return
     * @throws Exception
     */
    public static String HttpClientPost(String url , String charset , String[] keys , String[] values) throws Exception{
        HttpClient client = null;
        PostMethod post = null;
        String result = "";
        int status = 200;
        try {
               client = new HttpClient();
               //PostMethod对象用于存放地址
             //总账户的测试方法
               post = new PostMethod(url);
               //NameValuePair数组对象用于传入参数
               post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charset);//在头文件中设置转码

               String key = "";
               String value = "";
               NameValuePair temp = null;
               NameValuePair[] params = new NameValuePair[keys.length];
               for (int i = 0; i < keys.length; i++) {
                   key = (String)keys[i];
                   value = (String)values[i];
                   temp = new NameValuePair(key , value);
                   params[i] = temp;
                   temp = null;
               }
              post.setRequestBody(params);
               //执行的状态
              status = client.executeMethod(post);
              logger.info("status = " + status);

              if(status == 200){
                  result = post.getResponseBodyAsString();
              }

        } catch (Exception ex) {
            // TODO: handle exception
            throw new Exception("通过httpClient进行post提交异常:" + ex.getMessage() + " status = " + status);
        }
        finally{
            post.releaseConnection();
        }
        return result;
    }

    /**
     * 字符串处理,如果输入字符串为null则返回"",否则返回本字符串去前后空格。
     * @param inputStr            输入字符串
     * @return    string             输出字符串
     */
    public static String doString(String inputStr){
        //如果为null返回""
        if(inputStr == null || "".equals(inputStr) || "null".equals(inputStr)){
            return "";
        }
        //否则返回本字符串把前后空格去掉
        return inputStr.trim();
    }

    /**
     * 对象处理,如果输入对象为null返回"",否则则返回本字符对象信息,去掉前后空格
     * @param object
     * @return
     */
    public static String doString(Object object){
        //如果为null返回""
        if(object == null || "null".equals(object) || "".equals(object)){
            return "";
        }
        //否则返回本字符串把前后空格去掉
        return object.toString().trim();
    }

}

请求的XML 案例如下

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:eapp="http://www.gmw9.com">
   <soapenv:Header>
      <wsse:Security  xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" mustUnderstand="0">
         <wsse:UsernameToken>
            <wsse:Username>amtf</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">aaa</wsse:Password>
         </wsse:UsernameToken>

      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
      <eapp:nmamtf>
         <eapp:amtf>041</eapp:amtf>
         <eapp:dzwps>77771</eapp:amtf>

      </eapp:nmamtf>
   </soapenv:Body>
</soapenv:Envelope>
时间: 2024-10-22 16:12:37

通过原生的java Http请求soap发布接口的相关文章

高性能Java序列化框架Fse发布

目录 高性能Java序列化框架Fse发布 使用场景 使用说明 开源地址 高性能Java序列化框架Fse发布 使用场景 将Java对象序列化为二进制数据进行保存,以及二进制数据反向序列化为Java对象,在很多场景中都有应用.比如将对象序列化后离线存储至其他介质,或者存储于Redis这样的缓存之中. 目前常见的有几种框架可以支撑,比如 Hession ,Kryo,Protobuf,JDK原生等.有一些框架需要提前编写元数据配置文件以支撑跨语言序列化能力,比如 Protobuf .不过如果团队的技术栈

开源 java CMS - FreeCMS2.0发布。

FreeCMS商业版V2.0更新功能 1.标签参数不区分大小写,如向infoList标签传递siteid参数,参数名为siteid或SiteId都可以正确传递参数. 2.增加清空索引功能. 3.增加信息五星评分功能. 4.增加数据模型:站点.栏目.信息,可自由扩展自定义字段. 支持输入方式: 文本框(单行) 文本框(多行) 富文本编辑器 复选列表(checkbox) 单选列表(radio) 下拉列表(select单选) 日期选择框 日期时间选择框 支持验证方式: 中文 英文 Email格式 网址

java判断请求是否为ajax请求

/** * isAjaxRequest:判断请求是否为Ajax请求. <br/> * @param request 请求对象 * @return boolean * @since JDK 1.6 */ public boolean isAjaxRequest(HttpServletRequest request){ String header = request.getHeader("X-Requested-With"); boolean isAjax = "XM

java http请求

package com.expai.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.M

使用原生JavaScript发送ajax请求

关于使用原生JavaScript发送异步请求给服务端. 准备工作: 代码编写工具用的是sublime 服务端使用的是wamp搭的一个本地Apache服务器,主要用来返回数据 方便测试 步骤: 浏览器端 html标签绑定事件发送ajax请求----> 五步操作:1 创建异步对象XMLHttpRequest; 2 设置method url 3 发送请求给服务端 4 注册事件   5 在事件中获取服务端返回的数据,进行操作. 服务器端 1 获取请求数据 2 返回结果给浏览器 下面来一个小demo1做一

使用WSDL发布WebService(第二部分)简单对象访问协议——学习SOAP语法和使用SOAP发布WSDL

使用WSDL发布WebService(第二部分)简单对象访问协议——学习SOAP语法和使用SOAP发布WSDL http://www.ibm.com/developerworks/cn/webservices/ws-intwsdl/part2/#Listing1

Java httpclient请求,解决乱码问题

public class HttpPostRequestUtil { public HttpPostRequestUtil() { } public static String post(String url, Map<String, String> maps) { // 第一步,创建HttpPost对象 HttpPost httpPost = new HttpPost(url); // 设置HTTP POST请求参数必须用NameValuePair对象 List<NameValuePa

原生javaScript完成Ajax请求

使用原生javaScript完成Ajax请求,首先应该创建一个对象XMLHttprequest,考虑到兼容低版本IE浏览器,使用ActiveXObject对象,代码入下: var request; if(windoe.XMLHtprequest){ request=new XMLHttprequest(); }else{ request = new ActiveXObject(); } function success(text) { var textarea = document.getEle

Java获取请求客户端的真实IP地址

Java获取请求客户端的真实IP地址 Java,获取客户端的IP地址的方法: request.getRemoteAddr() 这种方法在大部分情况下都是有效的.但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了; 如果使用了反向代理软件,将http://192.168.1.110:2046 的URL反向代理为 http://www.javapeixun.com.cn的URL时, 用 request.getRemoteAddr() 方法获取的IP地址是:127.0