經過原生的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 案例以下java

<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>
相關文章
相關標籤/搜索