简单入门例子:WebService客户端请求

1、例子1

package soapDemo;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * 翻译TranslatorWebService
 * https://www.cnblogs.com/garfieldcgf/p/5966317.html
 */
public class TranslateDemo {

    public static void translate(String word ) throws Exception {
        //地址
        String urlString = "http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx ";
        //方法
        String soapActionString = "http://WebXml.com.cn/getEnCnTwoWayTranslator";
        URL url = new URL(urlString);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        //拼接请求体,此处也可以在外面写xml文件然后读取,但是为了方便一个文件搞定,而且参数也比较好传递我们直接String拼接(直接将网页上的复制进来即可)
        String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                "    <soap:Body>\n" +
                "        <getEnCnTwoWayTranslator xmlns=\"http://WebXml.com.cn/\">\n" +
                "            <Word>" + word + "</Word>\n" +
                "        </getEnCnTwoWayTranslator>\n" +
                "    </soap:Body>\n" +
                "</soap:Envelope>";
        byte[] buf = soap.getBytes();
        //设置一些头参数
        httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        httpConn.setRequestProperty("soapActionString", soapActionString);
        httpConn.setRequestMethod("POST");
        //输入参数和输出结果
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        OutputStream out = httpConn.getOutputStream();
        out.write(buf);
        out.close();

        //最后合格解析结果大家就各显神通了,此处打印出解析的过程,最终得到翻译答案
        byte[] datas = readInputStream(httpConn.getInputStream());
        String result = new String(datas);
        System.out.println("result:" + result);
        System.out.println(result.substring(result.indexOf("string") - 1,result.lastIndexOf("string") + 7));
        System.out.println(result.substring(result.indexOf("string") - 1,result.lastIndexOf("string") + 7).replaceAll("</{0,1}(string)?>",""));
    }

    /**
     * 从输入流中读取数据
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }

    public static void main(String[] args) throws Exception {
        translate("sea");
    }
}
result:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<getEnCnTwoWayTranslatorResponse xmlns="http://WebXml.com.cn/"><getEnCnTwoWayTranslatorResult>
<string>sea: [ si: ]</string><string>n. 海,海洋 |</string>
</getEnCnTwoWayTranslatorResult>
</getEnCnTwoWayTranslatorResponse>
</soap:Body>
</soap:Envelope>

2、例子2

sharepointApp.xml

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
            <listName>通知</listName>
            <query>
                <Query></Query>
            </query>
            <viewFields>
                <ViewFields xmlns="" />
            </viewFields>
            <rowLimit>300</rowLimit>
            <queryOptions>
                <QueryOptions xmlns=""></QueryOptions>
            </queryOptions>
        </GetListItems>
    </soap:Body>
</soap:Envelope>
package soapDemo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class SharepointApp {

    /**
     * 
     */
    public static void sendSms() throws Exception {
        String urlString = "http://xxxx-app/xxxfw/_vti_bin/Lists.asmx";
        String xmlFile = SharepointApp.class.getClassLoader().getResource("sharepointApp.xml").getFile();
        String soapActionString = "http://schemas.microsoft.com/sharepoint/soap/GetListItems";
        URL url = new URL(urlString);
        byte[] buf = readFile(xmlFile);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        httpConn.setRequestProperty("soapActionString", soapActionString);
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        OutputStream out = httpConn.getOutputStream();
        out.write(buf);
        out.close();

        byte[] datas=readInputStream(httpConn.getInputStream());
        String result=new String(datas);
        //打印返回结果
        System.out.println("result:" + result);
    }

    public static byte[] readFile(String fileName) throws Exception {
        File file = new File(fileName);
        byte[] buf = new byte[(int) file.length()];
        InputStream input=new FileInputStream(fileName);
        input.read(buf);
        input.close();
        return buf;
    }

    /**
     * 文件内容替换
     * 
     * @param inFileName 源文件
     * @param from
     * @param to
     * @return 返回替换后文件
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static File replace(String inFileName, String from, String to)
            throws IOException, UnsupportedEncodingException {
        File inFile = new File(inFileName);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                new FileInputStream(inFile), "utf-8"));
        File outFile = new File(inFile + ".tmp");
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")));
        String reading;
        while ((reading = in.readLine()) != null) {
            out.println(reading.replaceAll(from, to));
        }
        out.close();
        in.close();
        //infile.delete(); //删除源文件
        //outfile.renameTo(infile); //对临时文件重命名
        return outFile;
    }

    /**
     * 从输入流中读取数据
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) !=-1 ){
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();//网页的二进制数据
        outStream.close();
        inStream.close();
        return data;
    }

    public static void main(String[] args) throws Exception{
        SharepointApp.sendSms();
    }
}
result:<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/"><GetListItemsResult><listitems xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
     xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
     xmlns:rs='urn:schemas-microsoft-com:rowset'
     xmlns:z='#RowsetSchema'>
<rs:data ItemCount="29">
   <z:row ows_ID='17' ows_ContentTypeId='0x0120005A6CB4FA7539A04A98B63CA2822111' ows_ContentType='文件夹'/>
   <z:row ows_ID='15' ows_ContentTypeId='0x0101006254C3AF89B40D44AA44254111111D' ows_ContentType='文档'/>
</rs:data>
</listitems></GetListItemsResult></GetListItemsResponse></soap:Body></soap:Envelope>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值