zoukankan      html  css  js  c++  java
  • java调用webservice

    java调用webservice


    package com;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.net.URL;
    import java.net.URLConnection;

    public class InvokeWS {
    public static void main(String[] args) {
    try {
    //以请求天气service为例
    String point ="http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
    //初始化请求传送的soap信息 soap格式从上面网站可以查到
    String soap = getSoapBody("重庆");
    //获取 建立至webservice节点的连接
    URL url = new URL(point);
    URLConnection con = url.openConnection();
    con.setUseCaches(false);
    con.setDoInput(true);
    con.setDoOutput(true);
    //设置请求header信息
    con.setRequestProperty("Content-Type", "text/xml; charset=gbk");
    con.setRequestProperty("Content-Length",String.valueOf(soap.length()));
    con.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getWeatherbyCityName");
    //发送请求内容 soap至服务端
    OutputStream out = con.getOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(out,"gbk");
    writer.write(soap);
    writer.flush();
    writer.close();
    //获取响应信息
    InputStream in = con.getInputStream();
    InputStreamReader reader = new InputStreamReader(in,"utf-8");
    BufferedReader br = new BufferedReader(reader);
    String str = br.readLine();
    while(str !=null){
    System.out.println(str);
    str = br.readLine();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    private static String getSoapBody(String name){
    StringBuffer sb = new StringBuffer();
    sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    sb.append("<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/\">");
    sb.append("<soap:Body>");
    sb.append("<getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">");
    sb.append("<theCityName>").append(name).append("</theCityName>");
    sb.append("</getWeatherbyCityName>");
    sb.append("</soap:Body>");
    sb.append("</soap:Envelope>");
    return sb.toString();
    }
    }

  • 相关阅读:
    LeetCode Missing Number (简单题)
    LeetCode Valid Anagram (简单题)
    LeetCode Single Number III (xor)
    LeetCode Best Time to Buy and Sell Stock II (简单题)
    LeetCode Move Zeroes (简单题)
    LeetCode Add Digits (规律题)
    DependencyProperty深入浅出
    SQL Server存储机制二
    WPF自定义RoutedEvent事件示例代码
    ViewModel命令ICommand对象定义
  • 原文地址:https://www.cnblogs.com/zhanggaosong/p/3014255.html
Copyright © 2011-2022 走看看