码迷,mamicode.com
首页 > 编程语言 > 详细

使用Java HttpURLConnection方式调用webService

时间:2019-01-15 11:54:05      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:filename   unit   catch   ora   append   edr   ESS   post   UNC   

第一步(读取配置文件):
public class PropertiesUtil {
    private static final Logger logger = LoggerFactory
            .getLogger(PropertiesUtil.class);
    private static Properties properties = null;
    private static String fileName = "/app.properties";
    static {
        properties = new Properties();
        try {
            properties.load(PropertiesUtil.class.getResourceAsStream(fileName));
        } catch (IOException e) {
            logger.error("加载配置文件失败", e);
        }
    }

    public static Properties getProperties() {
        return properties;
    }

    public static String getProp(String propName) {
        return properties.getProperty(propName);
    }
}

第二步:
public static Map<String, String> resultInterface(String id,String type, String jsonStr) {
    StringBuilder res = new StringBuilder();
    // 1:创建服务地址
    URL url;
    String resultUserName = PropertiesUtil.getProp("resultUserName");
    String resultPassWord = PropertiesUtil.getProp("resultPassWord");
    Map<String, String> map = new HashMap<String, String>();
    try {
      url = new URL(PropertiesUtil.getProp("resultUrl"));
      // 2:打开到服务地址的一个连接
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      // 3:设置连接参数
      // 3.1设置发送方式:POST必须大写
      connection.setRequestMethod("POST");
      // 3.2设置数据格式:Content-type
      connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
      // 3.3设置输入输出,新创建的connection默认是没有读写权限的,
      connection.setDoInput(true);
      connection.setDoOutput(true);
      //"{\"ANNOUNCEMENT_CODE\": \"CSGGBH001\",\"ANNOUNCEMENT_CONNECT\": \"asdfasdfasdfasdfasdfasdfasdfsa\",\"ANNOUNCEMENT_DEADLINE\": \"20181031\",\"ANNOUNCEMENT_GUID\": \"71F15848-C296-4A60-883C-223C55E9E8D8\",\"ANNOUNCEMENT_START_TIME\": \"20181101\",\"ANNOUNCEMENT_TITLE\": \"公告标题\",\"ANNOUNCEMENT_TYPE\": \"1\",\"ANNOUNCEMENT_UNIT\": \"单位\",\"ATTACHMENT_SET_CODE\": \"123\",\"CANCEL_REASON\": \"撤销理由\",\"CHANGE_TIME\": \"20181101\",\"CONTACT_NUMBER\": \"13333333333\",\"CONTACT_PERSON\": \"联系人\",\"CREATE_TIME\": \"20181101\",\"DATA_TIMESTAMP\": \"20181101154911\",\"EMAIL\": \"123@qq.com\",\"END_DATE\": \"20181101\",\"FIELD_NUM\": \"123\",\"LAND_DISTRICT\": \"440601\",\"LIAISON_UNIT\": \"单位\",\"LISTING_DEADLINE\": \"\",\"LISTING_START_TIME\": \"\",\"LISTING_TYPE\": \"0\",\"PLATFORM_CODE\": \"91441900708017879M\",\"PUBLISHING_TIME\": \"20181101\",\"PUB_SERVICE_PLAT_CODE\": \"123707003283632515\",\"RETREAT_TIME\": \"20181101\",\"SUPPLY_TYPE\": \"1\",\"UNIFIED_DEAL_CODE\": \"B01-123707003283632515-20181025-000015-V\",\"UNIT_ADDRESS\": \"单位地址\",\"URL\": \"http://www.baidu.com\",\"ZIP_CODE\": \"215600\"}";
      //TDJYGG
      // 4:组织SOAP协议数据,发送给服务端
      String soapXML = "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
          + "       <soap12:Header>                           "
          + "         <root xmlns=\"http://tempuri.org/\">      "
          + "           <UserName>"+resultUserName+"</UserName>           "
          + "           <PassWord>"+resultPassWord+"</PassWord>           "
          + "         </root>                                 "
          + "       </soap12:Header>                          "
          + "       <soap12:Body>                             "
          + "         <Push xmlns=\"http://tempuri.org/\">      "
          + "           <Type>"+type+"</Type>                   "
          + "           <JsonStr>"+jsonStr+"</JsonStr>"
          + "         </Push>                                 "
          + "       </soap12:Body>                            "
          + "     </soap12:Envelope>";
      OutputStream os = connection.getOutputStream();
      os.write(soapXML.getBytes());

      // 5:接收服务端的响应
      int responseCode = connection.getResponseCode();
      if (200 == responseCode) {// 表示服务端响应成功
        InputStream is = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String temp = null;
        while (null != (temp = br.readLine())) {
          res.append(temp);
        }
        
        is.close();
        isr.close();
        br.close();
        String xml = res.toString();
        Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点
        //System.out.println("根节点:" + rootElt.getStringValue()); 
        
        Element nameElem = rootElt.element("Body").element("PushResponse").element("PushResult");
        String code = nameElem.element("Code").getTextTrim();
        String description = nameElem.element("Description").getTextTrim();
        map.put("code", code);
        map.put("description", description);
      } else {
        //res.append("调接口异常!");
        map.put("code", "500");
        map.put("description", "数据推送失败,服务端响应失败!");
        logger.error("数据推送失败,服务端响应失败!");
      }
      os.close();
    } catch (Exception e) {
      //res.append("调接口异常!");
      map.put("code", "500");
      map.put("description", "数据推送异常,推送信息为trans_notice表或trans_target表的id>>>>:" + id);
      logger.error("数据推送异常,推送信息为trans_notice表或trans_target表的id>>>>:" + id + "", e);
    }
    
    return map;
  }

 

public static Map<String, String> resultInterface(String id,String type, String jsonStr) {    StringBuilder res = new StringBuilder();    // 1:创建服务地址    URL url;    String resultUserName = PropertiesUtil.getProp("resultUserName");    String resultPassWord = PropertiesUtil.getProp("resultPassWord");    Map<String, String> map = new HashMap<String, String>();    try {      url = new URL(PropertiesUtil.getProp("resultUrl"));      // 2:打开到服务地址的一个连接      HttpURLConnection connection = (HttpURLConnection) url.openConnection();      // 3:设置连接参数      // 3.1设置发送方式:POST必须大写      connection.setRequestMethod("POST");      // 3.2设置数据格式:Content-type      connection.setRequestProperty("content-type", "text/xml;charset=utf-8");      // 3.3设置输入输出,新创建的connection默认是没有读写权限的,      connection.setDoInput(true);      connection.setDoOutput(true);      //"{\"ANNOUNCEMENT_CODE\": \"CSGGBH001\",\"ANNOUNCEMENT_CONNECT\": \"asdfasdfasdfasdfasdfasdfasdfsa\",\"ANNOUNCEMENT_DEADLINE\": \"20181031\",\"ANNOUNCEMENT_GUID\": \"71F15848-C296-4A60-883C-223C55E9E8D8\",\"ANNOUNCEMENT_START_TIME\": \"20181101\",\"ANNOUNCEMENT_TITLE\": \"公告标题\",\"ANNOUNCEMENT_TYPE\": \"1\",\"ANNOUNCEMENT_UNIT\": \"单位\",\"ATTACHMENT_SET_CODE\": \"123\",\"CANCEL_REASON\": \"撤销理由\",\"CHANGE_TIME\": \"20181101\",\"CONTACT_NUMBER\": \"13333333333\",\"CONTACT_PERSON\": \"联系人\",\"CREATE_TIME\": \"20181101\",\"DATA_TIMESTAMP\": \"20181101154911\",\"EMAIL\": \"123@qq.com\",\"END_DATE\": \"20181101\",\"FIELD_NUM\": \"123\",\"LAND_DISTRICT\": \"440601\",\"LIAISON_UNIT\": \"单位\",\"LISTING_DEADLINE\": \"\",\"LISTING_START_TIME\": \"\",\"LISTING_TYPE\": \"0\",\"PLATFORM_CODE\": \"91441900708017879M\",\"PUBLISHING_TIME\": \"20181101\",\"PUB_SERVICE_PLAT_CODE\": \"123707003283632515\",\"RETREAT_TIME\": \"20181101\",\"SUPPLY_TYPE\": \"1\",\"UNIFIED_DEAL_CODE\": \"B01-123707003283632515-20181025-000015-V\",\"UNIT_ADDRESS\": \"单位地址\",\"URL\": \"http://www.baidu.com\",\"ZIP_CODE\": \"215600\"}";      //TDJYGG      // 4:组织SOAP协议数据,发送给服务端      String soapXML = "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"          + "       <soap12:Header>                           "          + "         <root xmlns=\"http://tempuri.org/\">      "          + "           <UserName>"+resultUserName+"</UserName>           "          + "           <PassWord>"+resultPassWord+"</PassWord>           "          + "         </root>                                 "          + "       </soap12:Header>                          "          + "       <soap12:Body>                             "          + "         <Push xmlns=\"http://tempuri.org/\">      "          + "           <Type>"+type+"</Type>                   "          + "           <JsonStr>"+jsonStr+"</JsonStr>"          + "         </Push>                                 "          + "       </soap12:Body>                            "          + "     </soap12:Envelope>";      OutputStream os = connection.getOutputStream();      os.write(soapXML.getBytes());
      // 5:接收服务端的响应      int responseCode = connection.getResponseCode();      if (200 == responseCode) {// 表示服务端响应成功        InputStream is = connection.getInputStream();        InputStreamReader isr = new InputStreamReader(is);        BufferedReader br = new BufferedReader(isr);        String temp = null;        while (null != (temp = br.readLine())) {          res.append(temp);        }                is.close();        isr.close();        br.close();        String xml = res.toString();        Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML        Element rootElt = doc.getRootElement(); // 获取根节点        //System.out.println("根节点:" + rootElt.getStringValue());                 Element nameElem = rootElt.element("Body").element("PushResponse").element("PushResult");        String code = nameElem.element("Code").getTextTrim();        String description = nameElem.element("Description").getTextTrim();        map.put("code", code);        map.put("description", description);      } else {        //res.append("调接口异常!");        map.put("code", "500");        map.put("description", "数据推送失败,服务端响应失败!");        logger.error("数据推送失败,服务端响应失败!");      }      os.close();    } catch (Exception e) {      //res.append("调接口异常!");      map.put("code", "500");      map.put("description", "数据推送异常,推送信息为trans_notice表或trans_target表的id>>>>:" + id);      logger.error("数据推送异常,推送信息为trans_notice表或trans_target表的id>>>>:" + id + "", e);    }        return map;  }

使用Java HttpURLConnection方式调用webService

标签:filename   unit   catch   ora   append   edr   ESS   post   UNC   

原文地址:https://www.cnblogs.com/gaomanito/p/10270688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!