你的位置:首页 > Java教程

[Java教程]HttpURLConnection 直接发送soap消息调用webservice


package com.travelsky.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;


public class Test {


    private String testConn(String         String urlString = "http://IP/3uffpWS/3uffpWebService.asmx";
        HttpURLConnection httpConn = null;
        OutputStream out = null;
        String return        System.out.println("开始.......");
        try {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("IP", 端口));
            
            httpConn = (HttpURLConnection) new URL(urlString).openConnection(proxy);
            httpConn.setRequestProperty("Content-Type","text/            httpConn.setRequestProperty("soapActionString", "http://tempuri.org/_3uffpWS/_3uffpWebService/ReturnSmsValidateCode");
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.connect();
            out = httpConn.getOutputStream(); // 获取输出流对象
            httpConn.getOutputStream().write(            out.flush();
            out.close();
            int code = httpConn.getResponseCode(); // 用来获取服务器响应状态
            String tempString = null;
            StringBuffer sb1 = new StringBuffer();
            System.out.println("code="+code);
            if (code == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
                while ( (tempString = reader.readLine()) != null ) {
                    sb1.append(tempString);
                }
                if (null != reader) {
                    reader.close();
                }
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(),"UTF-8"));
                // 一次读入一行,直到读入null为文件结束
                while ( (tempString = reader.readLine()) != null ) {
                    sb1.append(tempString);
                }
                if (null != reader) {
                    reader.close();
                }
            }
            // 响应报文
            return            System.out.println("结束.......");
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return return    }
    

    public static void main(String[] args) {

        String             +"<soap:Envelope             +"<soap:Body>"
            +"<ReturnSmsValidateCode             +"<memberID>string</memberID>"
            +"<validateNumUserInput>15801286875</validateNumUserInput>"
            +"</ReturnSmsValidateCode>"
            +"</soap:Body>"
            +"</soap:Envelope>";
        
        String r = new Test().testConn(        System.out.println(r);
    }
}